Welcome to mirror list, hosted at ThFree Co, Russian Federation.

framework.cpp « map - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 680e27a66467780357ab8eb53268a369e4fb11fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
#include "../base/SRC_FIRST.hpp"

#include "framework.hpp"
#include "draw_processor.hpp"
#include "drawer_yg.hpp"
#include "feature_vec_model.hpp"
#include "benchmark_provider.hpp"
#include "languages.hpp"

#include "../search/engine.hpp"
#include "../search/result.hpp"
#include "../search/categories_holder.hpp"

#include "../indexer/feature_visibility.hpp"
#include "../indexer/feature.hpp"
#include "../indexer/scales.hpp"
#include "../indexer/drawing_rules.hpp"

#include "../base/math.hpp"
#include "../base/string_utils.hpp"

#include "../std/algorithm.hpp"
#include "../std/fstream.hpp"

#include "../version/version.hpp"

#include "../yg/internal/opengl.hpp"
#include "../yg/info_layer.hpp"

using namespace feature;

namespace fwork
{
  namespace
  {
    template <class TSrc> void assign_point(di::DrawInfo * p, TSrc & src)
    {
      p->m_point = src.m_point;
    }
    template <class TSrc> void assign_path(di::DrawInfo * p, TSrc & src)
    {
      p->m_pathes.swap(src.m_points);
    }
    template <class TSrc> void assign_area(di::DrawInfo * p, TSrc & src)
    {
      p->m_areas.swap(src.m_points);

      ASSERT ( !p->m_areas.empty(), () );
      p->m_areas.back().SetCenter(src.GetCenter());
    }
  }

  DrawProcessor::DrawProcessor( m2::RectD const & r,
                                ScreenBase const & convertor,
                                shared_ptr<PaintEvent> const & paintEvent,
                                int scaleLevel,
                                shared_ptr<yg::gl::RenderState> const & renderState,
                                yg::GlyphCache * glyphCache)
    : m_rect(r),
      m_convertor(convertor),
      m_paintEvent(paintEvent),
      m_zoom(scaleLevel),
      m_renderState(renderState),
      m_glyphCache(glyphCache)
#ifdef PROFILER_DRAWING
      , m_drawCount(0)
#endif
  {
    m_keys.reserve(reserve_rules_count);

    GetDrawer()->SetScale(m_zoom);
  }

  namespace
  {
    struct less_depth
    {
      bool operator() (di::DrawRule const & r1, di::DrawRule const & r2) const
      {
        return (r1.m_depth < r2.m_depth);
      }
    };

    struct less_key
    {
      bool operator() (drule::Key const & r1, drule::Key const & r2) const
      {
        if (r1.m_type == r2.m_type)
        {
          // assume that unique algo leaves the first element (with max priority), others - go away
          return (r1.m_priority > r2.m_priority);
        }
        else
          return (r1.m_type < r2.m_type);
      }
    };

    struct equal_key
    {
      bool operator() (drule::Key const & r1, drule::Key const & r2) const
      {
        // many line and area rules - is ok, other rules - one is enough
        if (r1.m_type == drule::line || r1.m_type == drule::area)
          return (r1 == r2);
        else
          return (r1.m_type == r2.m_type);
      }
    };
  }

  void DrawProcessor::PreProcessKeys()
  {
    sort(m_keys.begin(), m_keys.end(), less_key());
    m_keys.erase(unique(m_keys.begin(), m_keys.end(), equal_key()), m_keys.end());
  }

#define GET_POINTS(f, for_each_fun, fun, assign_fun)       \
  {                                                        \
    f.for_each_fun(fun, m_zoom);                           \
    if (fun.IsExist())                                     \
    {                                                      \
      isExist = true;                                      \
      assign_fun(ptr.get(), fun);                          \
    }                                                      \
  }

  bool DrawProcessor::operator()(FeatureType const & f)
  {
    if (m_paintEvent->isCancelled())
      throw redraw_operation_cancelled();

    // get drawing rules
    m_keys.clear();
    string names;       // for debug use only, in release it's empty
    int type = feature::GetDrawRule(f, m_zoom, m_keys, names);

    if (m_keys.empty())
    {
      // Index can pass here invisible features.
      // During indexing, features are placed at first visible scale bucket.
      // At higher scales it can become invisible - it depends on classificator.
      return true;
    }

    // remove duplicating identical drawing keys
    PreProcessKeys();

    // get drawing rules for the m_keys array
    size_t const count = m_keys.size();
#ifdef PROFILER_DRAWING
    m_drawCount += count;
#endif

    buffer_vector<di::DrawRule, reserve_rules_count> rules;
    rules.resize(count);

    int layer = f.GetLayer();
    bool isTransparent = false;
    if (layer == feature::LAYER_TRANSPARENT_TUNNEL)
    {
      layer = 0;
      isTransparent = true;
    }

    for (size_t i = 0; i < count; ++i)
    {
      int depth = m_keys[i].m_priority;
      if (layer != 0)
        depth = (layer * drule::layer_base_priority) + (depth % drule::layer_base_priority);

      rules[i] = di::DrawRule(drule::rules().Find(m_keys[i]), depth, isTransparent);
    }

    sort(rules.begin(), rules.end(), less_depth());

    m_renderState->m_isEmptyModelCurrent = false;

    shared_ptr<di::DrawInfo> ptr(new di::DrawInfo(
      f.GetPreferredDrawableName(languages::GetCurrentPriorities()),
      f.GetRoadNumber(),
      (m_zoom > 5) ? f.GetPopulationDrawRank() : 0.0));

    DrawerYG * pDrawer = GetDrawer();

    using namespace get_pts;

    bool isExist = false;
    switch (type)
    {
    case GEOM_POINT:
    {
      typedef get_pts::one_point functor_t;

      functor_t::params p;
      p.m_convertor = &m_convertor;
      p.m_rect = &m_rect;

      functor_t fun(p);
      GET_POINTS(f, ForEachPointRef, fun, assign_point)
      break;
    }

    case GEOM_AREA:
    {
      typedef filter_screenpts_adapter<area_tess_points> functor_t;

      functor_t::params p;
      p.m_convertor = &m_convertor;
      p.m_rect = &m_rect;

      functor_t fun(p);
      GET_POINTS(f, ForEachTriangleExRef, fun, assign_area)
      {
        // if area feature has any line-drawing-rules, than draw it like line
        for (size_t i = 0; i < m_keys.size(); ++i)
          if (m_keys[i].m_type == drule::line)
            goto draw_line;
        break;
      }
    }
    draw_line:
    case GEOM_LINE:
      {
        typedef filter_screenpts_adapter<path_points> functor_t;
        functor_t::params p;
        p.m_convertor = &m_convertor;
        p.m_rect = &m_rect;

        if (!ptr->m_name.empty())
        {
          double fontSize = 0;
          for (size_t i = 0; i < count; ++i)
          {
            if (pDrawer->filter_text_size(rules[i].m_rule))
              fontSize = max((uint8_t)fontSize, pDrawer->get_pathtext_font_size(rules[i].m_rule));
          }

          if (fontSize != 0)
          {
            double textLength = m_glyphCache->getTextLength(fontSize, ptr->m_name);
            typedef calc_length<base_global> functor_t;
            functor_t::params p1;
            p1.m_convertor = &m_convertor;
            p1.m_rect = &m_rect;
            functor_t fun(p1);

            f.ForEachPointRef(fun, m_zoom);
            if ((fun.IsExist()) && (fun.m_length > textLength))
            {
              textLength += 50;
              p.m_startLength = (fun.m_length - textLength) / 2;
              p.m_endLength = p.m_startLength + textLength;
            }
          }
        }

        functor_t fun(p);

        GET_POINTS(f, ForEachPointRef, fun, assign_path)

        break;
      }
    }

    if (isExist)
      pDrawer->Draw(ptr.get(), rules.data(), count);

    return true;
  }
}

template <typename TModel>
void FrameWork<TModel>::AddRedrawCommandSure()
{
  m_renderQueue.AddCommand(bind(&this_type::PaintImpl, this, _1, _2, _3, _4), m_navigator.Screen());
}

  template <typename TModel>
  void FrameWork<TModel>::AddRedrawCommand()
  {
    yg::gl::RenderState const state = m_renderQueue.CopyState();
    if ((state.m_currentScreen != m_navigator.Screen()) && (m_isRedrawEnabled))
      AddRedrawCommandSure();
  }

  template <typename TModel>
  void FrameWork<TModel>::AddMap(ReaderT const & file)
  {
    // update rect for Show All button
    feature::DataHeader header;
    header.Load(FilesContainerR(file).GetReader(HEADER_FILE_TAG));

    m2::RectD bounds = header.GetBounds();

    m_model.AddWorldRect(bounds);
    {
      threads::MutexGuard lock(m_modelSyn);
      m_model.AddMap(file);
    }
  }

  template <typename TModel>
  void FrameWork<TModel>::RemoveMap(string const & datFile)
  {
    threads::MutexGuard lock(m_modelSyn);
    m_model.RemoveMap(datFile);
  }

  template <typename TModel>
  void FrameWork<TModel>::OnGpsUpdate(location::GpsInfo const & info)
  {
    // notify GUI that we received gps position
    if (!(m_locationState & location::State::EGps) && m_locationObserver)
      m_locationObserver();

    m_locationState.UpdateGps(info);
    if (m_centeringMode == ECenterAndScale)
    {
      CenterAndScaleViewport();
      m_centeringMode = ECenterOnly;
    }
    else if (m_centeringMode == ECenterOnly)
      CenterViewport(m_locationState.Position());
    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::OnCompassUpdate(location::CompassInfo const & info)
  {
    if (info.m_timestamp < location::POSITION_TIMEOUT_SECONDS)
    {
      m_locationState.UpdateCompass(info);
      UpdateNow();
    }
  }

  template <typename TModel>
  FrameWork<TModel>::FrameWork(shared_ptr<WindowHandle> windowHandle,
            size_t bottomShift)
    : m_windowHandle(windowHandle),
      m_isBenchmarking(GetPlatform().IsBenchmarking()),
      m_isBenchmarkInitialized(false),
      m_bgColor(0xEE, 0xEE, 0xDD, 0xFF),
      m_renderQueue(GetPlatform().SkinName(),
                    GetPlatform().IsMultiSampled() && yg::gl::g_isMultisamplingSupported,
                    GetPlatform().DoPeriodicalUpdate(),
                    GetPlatform().PeriodicalUpdateInterval(),
                    GetPlatform().IsBenchmarking(),
                    GetPlatform().ScaleEtalonSize(),
                    m_bgColor),
      m_isRedrawEnabled(true),
      m_metresMinWidth(20),
      m_minRulerWidth(97),
      m_centeringMode(EDoNothing),
      m_maxDuration(0),
      m_tileSize(512)
  {
    m_startTime = my::FormatCurrentTime();

    m_informationDisplay.setBottomShift(bottomShift);
#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.enableDebugPoints(true);
#endif

#ifdef DEBUG
    m_informationDisplay.enableGlobalRect(!m_isBenchmarking);
#endif

    m_informationDisplay.enableCenter(true);

    m_informationDisplay.enableRuler(true);
    m_informationDisplay.setRulerParams(m_minRulerWidth, m_metresMinWidth);
    m_navigator.SetMinScreenParams(m_minRulerWidth, m_metresMinWidth);

#ifdef DEBUG
    m_informationDisplay.enableDebugInfo(true);
#endif

    m_informationDisplay.enableLog(GetPlatform().IsVisualLog(), m_windowHandle.get());

    m_informationDisplay.enableBenchmarkInfo(m_isBenchmarking);

    m_informationDisplay.setVisualScale(GetPlatform().VisualScale());
    m_renderQueue.AddWindowHandle(m_windowHandle);

    // initialize gps and compass subsystem
    GetLocationManager().SetGpsObserver(
          bind(&this_type::OnGpsUpdate, this, _1));
    GetLocationManager().SetCompassObserver(
          bind(&this_type::OnCompassUpdate, this, _1));

    // set language priorities
    languages::CodesT langCodes;
    languages::GetCurrentSettings(langCodes);
    languages::SaveSettings(langCodes);
  }

  template <typename TModel>
  FrameWork<TModel>::~FrameWork()
  {
  }

  template <typename TModel>
  void FrameWork<TModel>::BenchmarkCommandFinished()
  {
    double duration = m_renderQueue.renderState().m_duration;
    if (duration > m_maxDuration)
    {
      m_maxDuration = duration;
      m_maxDurationRect = m_curBenchmarkRect;
      m_informationDisplay.addBenchmarkInfo("maxDurationRect: ", m_maxDurationRect, m_maxDuration);
    }

    BenchmarkResult res;
    res.m_name = m_benchmarks[m_curBenchmark].m_name;
    res.m_rect = m_curBenchmarkRect;
    res.m_time = duration;
    m_benchmarkResults.push_back(res);

    if (m_benchmarkResults.size() > 100)
      SaveBenchmarkResults();

    NextBenchmarkCommand();
  }

  template <typename TModel>
  void FrameWork<TModel>::SaveBenchmarkResults()
  {
    ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);

    for (size_t i = 0; i < m_benchmarkResults.size(); ++i)
    {
      fout << GetPlatform().DeviceID() << " "
           << VERSION_STRING << " "
           << m_startTime << " "
           << m_benchmarkResults[i].m_name << " "
           << m_benchmarkResults[i].m_rect.minX() << " "
           << m_benchmarkResults[i].m_rect.minY() << " "
           << m_benchmarkResults[i].m_rect.maxX() << " "
           << m_benchmarkResults[i].m_rect.maxY() << " "
           << m_benchmarkResults[i].m_time << endl;
    }

    m_benchmarkResults.clear();
  }

  template <typename TModel>
  void FrameWork<TModel>::SendBenchmarkResults()
  {
//    ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);
//    fout << "[COMPLETED]";
//    fout.close();
    /// send to server for adding to statistics graphics
    /// and delete results file
  }

  template <typename TModel>
  void FrameWork<TModel>::MarkBenchmarkResultsEnd()
  {
    ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);
    fout << "END " << m_startTime << endl;
  }

  template <typename TModel>
  void FrameWork<TModel>::MarkBenchmarkResultsStart()
  {
    ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);
    fout << "START " << m_startTime << endl;
  }

  template <typename TModel>
  void FrameWork<TModel>::NextBenchmarkCommand()
  {
    if ((m_benchmarks[m_curBenchmark].m_provider->hasRect()) || (++m_curBenchmark < m_benchmarks.size()))
    {
      m_curBenchmarkRect = m_benchmarks[m_curBenchmark].m_provider->nextRect();
      m_navigator.SetFromRect(m_curBenchmarkRect);
      m_renderQueue.AddBenchmarkCommand(bind(&this_type::PaintImpl, this, _1, _2, _3, _4), m_navigator.Screen());
    }
    else
    {
      SaveBenchmarkResults();
      MarkBenchmarkResultsEnd();
      SendBenchmarkResults();
      LOG(LINFO, ("Bechmarks took ", m_benchmarksTimer.ElapsedSeconds(), " seconds to complete"));
    }
  }

  struct PathAppender
  {
    string const & m_path;
    PathAppender(string const & path) : m_path(path) {}
    void operator()(string & elem)
    {
      elem.insert(elem.begin(), m_path.begin(), m_path.end());
    }
  };

  class ReadersAdder
  {
    typedef vector<ModelReaderPtr> maps_list_t;

    Platform & m_pl;
    maps_list_t & m_lst;

  public:
    ReadersAdder(Platform & pl, maps_list_t & lst) : m_pl(pl), m_lst(lst) {}

    void operator() (string const & f)
    {
      m_lst.push_back(m_pl.GetReader(f));
    }
  };

  template <typename TModel>
  void FrameWork<TModel>::EnumLocalMaps(maps_list_t & filesList)
  {
    Platform & pl = GetPlatform();

    // scan for pre-installed maps in resources
    string const resPath = pl.ResourcesDir();
    Platform::FilesList resFiles;
    pl.GetFilesInDir(resPath, "*" DATA_FILE_EXTENSION, resFiles);

    // scan for probably updated maps in data dir
    string const dataPath = pl.WritableDir();
    Platform::FilesList dataFiles;
    pl.GetFilesInDir(dataPath, "*" DATA_FILE_EXTENSION, dataFiles);

    // wipe out same maps from resources, which have updated
    // downloaded versions in data path
    for (Platform::FilesList::iterator it = resFiles.begin(); it != resFiles.end();)
    {
      Platform::FilesList::iterator found = find(dataFiles.begin(), dataFiles.end(), *it);
      if (found != dataFiles.end())
        it = resFiles.erase(it);
      else
        ++it;
    }

    filesList.clear();
    for_each(resFiles.begin(), resFiles.end(), ReadersAdder(pl, filesList));
    for_each(dataFiles.begin(), dataFiles.end(), ReadersAdder(pl, filesList));
  }

  template <typename TModel>
  void FrameWork<TModel>::EnumBenchmarkMaps(maps_list_t & filesList)
  {
    Platform & pl = GetPlatform();

    set<string> files;
    ifstream fin(pl.WritablePathForFile("benchmarks/config.info").c_str());

    filesList.clear();
    char buf[256];

    while (true)
    {
      fin.getline(buf, 256);

      if (!fin)
        break;

      vector<string> parts;
      string s(buf);
      strings::SimpleTokenizer it(s, " ");
      while (it)
      {
        parts.push_back(*it);
        ++it;
      }

      filesList.push_back(pl.GetReader(parts[0]));
    }
  }

  template <typename TModel>
  void FrameWork<TModel>::InitBenchmark()
  {
    //m2::RectD wr(MercatorBounds::minX, MercatorBounds::minY, MercatorBounds::maxX, MercatorBounds::maxY);
    //m2::RectD r(wr.Center().x, wr.Center().y + wr.SizeY() / 8, wr.Center().x + wr.SizeX() / 8, wr.Center().y + wr.SizeY() / 4);

    set<string> files;
    ifstream fin(GetPlatform().WritablePathForFile("benchmarks/config.info").c_str());
    while (true)
    {
      string name;
      m2::RectD r;

      char buf[256];

      fin.getline(buf, 256);

      if (!fin)
        break;

      vector<string> parts;
      string s(buf);
      strings::SimpleTokenizer it(s, " ");
      while (it)
      {
        parts.push_back(*it);
        ++it;
      }

      Benchmark b;
      b.m_name = parts[1];

      if (files.find(parts[0]) == files.end())
      {
        files.insert(parts[0]);
        if (GetPlatform().IsFileExists(GetPlatform().WritablePathForFile(parts[0])))
        {
          try
          {
            feature::DataHeader header;
            header.Load(FilesContainerR(GetPlatform().WritablePathForFile(parts[0])).GetReader(HEADER_FILE_TAG));

            r = header.GetBounds();
          }
          catch (std::exception const &)
          {
            LOG(LINFO, ("cannot add ", parts[0], " file to benchmark"));
          }
        }
      }

      int lastScale;

      LOG(LINFO, (parts));
      if (parts.size() > 3)
      {
        double x0, y0, x1, y1;
        strings::to_double(parts[2], x0);
        strings::to_double(parts[3], y0);
        strings::to_double(parts[4], x1);
        strings::to_double(parts[5], y1);
        r = m2::RectD(x0, y0, x1, y1);
        strings::to_int(parts[6], lastScale);
      }
      else
        strings::to_int(parts[2], lastScale);

      b.m_provider.reset(new BenchmarkRectProvider(scales::GetScaleLevel(r), r, lastScale));

      m_benchmarks.push_back(b);
    }

    m_curBenchmark = 0;

    m_renderQueue.addRenderCommandFinishedFn(bind(&this_type::BenchmarkCommandFinished, this));
    m_benchmarksTimer.Reset();

    MarkBenchmarkResultsStart();
    NextBenchmarkCommand();

    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::initializeGL(shared_ptr<yg::gl::RenderContext> const & primaryContext,
                    shared_ptr<yg::ResourceManager> const & resourceManager)
  {
    m_resourceManager = resourceManager;
    m_renderQueue.initializeGL(primaryContext, m_resourceManager, GetPlatform().VisualScale());
  }

  template <typename TModel>
  TModel & FrameWork<TModel>::get_model()
  {
    return m_model;
  }

  template <typename TModel>
  void FrameWork<TModel>::StartLocationService(LocationRetrievedCallbackT observer)
  {
    m_locationObserver = observer;
    m_centeringMode = ECenterAndScale;
    // by default, we always start in accurate mode
    GetLocationManager().StartUpdate(true);
  }

  template <typename TModel>
  void FrameWork<TModel>::StopLocationService()
  {
    // reset callback
    m_locationObserver.clear();
    m_centeringMode = EDoNothing;
    GetLocationManager().StopUpdate();
    m_locationState.TurnOff();
    Invalidate();
  }

  template <typename TModel>
  bool FrameWork<TModel>::IsEmptyModel()
  {
    return m_model.GetWorldRect() == m2::RectD::GetEmptyRect();
  }

  // Cleanup.
  template <typename TModel>
  void FrameWork<TModel>::Clean()
  {
    m_model.Clean();
  }

  template <typename TModel>
  void FrameWork<TModel>::PrepareToShutdown()
  {
    if (m_pSearchEngine)
      m_pSearchEngine->StopEverything();
  }

  template <typename TModel>
  void FrameWork<TModel>::SetMaxWorldRect()
  {
    m_navigator.SetFromRect(m_model.GetWorldRect());
  }

  template <typename TModel>
  void FrameWork<TModel>::UpdateNow()
  {
    AddRedrawCommand();
    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::Invalidate()
  {
    m_windowHandle->invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::SaveState()
  {
    m_navigator.SaveState();
  }

  template <typename TModel>
  bool FrameWork<TModel>::LoadState()
  {
    if (!m_navigator.LoadState())
      return false;

    return true;
  }
  //@}

  /// Resize event from window.
  template <typename TModel>
  void FrameWork<TModel>::OnSize(int w, int h)
  {
    if (w < 2) w = 2;
    if (h < 2) h = 2;

    m_renderQueue.OnSize(w, h);

    m2::PointU ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m_informationDisplay.setDisplayRect(m2::RectI(ptShift, ptShift + m2::PointU(w, h)));

    m_navigator.OnSize(ptShift.x, ptShift.y, w, h);

    if ((m_isBenchmarking) && (!m_isBenchmarkInitialized))
    {
      m_isBenchmarkInitialized = true;
      InitBenchmark();
    }
  }

  template <typename TModel>
  bool FrameWork<TModel>::SetUpdatesEnabled(bool doEnable)
  {
    return m_windowHandle->setUpdatesEnabled(doEnable);
  }

  /// enabling/disabling AddRedrawCommand
  template <typename TModel>
  void FrameWork<TModel>::SetRedrawEnabled(bool isRedrawEnabled)
  {
    m_isRedrawEnabled = isRedrawEnabled;
    AddRedrawCommand();
  }

  /// respond to device orientation changes
  template <typename TModel>
  void FrameWork<TModel>::SetOrientation(EOrientation orientation)
  {
    m_navigator.SetOrientation(orientation);
    m_locationState.SetOrientation(orientation);
    UpdateNow();
  }

  template <typename TModel>
  double FrameWork<TModel>::GetCurrentScale() const
  {
    m2::PointD textureCenter(m_renderQueue.renderState().m_textureWidth / 2,
                             m_renderQueue.renderState().m_textureHeight / 2);
    m2::RectD glbRect;

    unsigned scaleEtalonSize = GetPlatform().ScaleEtalonSize();
    m_navigator.Screen().PtoG(m2::RectD(textureCenter - m2::PointD(scaleEtalonSize / 2, scaleEtalonSize / 2),
                                        textureCenter + m2::PointD(scaleEtalonSize / 2, scaleEtalonSize / 2)),
                              glbRect);
    return scales::GetScaleLevelD(glbRect);
  }

  /// Actual rendering function.
  /// Called, as the renderQueue processes RenderCommand
  /// Usually it happens in the separate thread.
  template <typename TModel>
  void FrameWork<TModel>::PaintImpl(shared_ptr<PaintEvent> e,
                 ScreenBase const & screen,
                 m2::RectD const & selectRect,
                 int scaleLevel
                 )
  {
    fwork::DrawProcessor doDraw(selectRect, screen, e, scaleLevel, m_renderQueue.renderStatePtr(), e->drawer()->screen()->glyphCache());
    m_renderQueue.renderStatePtr()->m_isEmptyModelCurrent = true;

    try
    {
      threads::MutexGuard lock(m_modelSyn);

#ifdef PROFILER_DRAWING
      using namespace prof;

      start<for_each_feature>();
      reset<feature_count>();
#endif

      m_model.ForEachFeatureWithScale(selectRect, bind<bool>(ref(doDraw), _1), scaleLevel);

#ifdef PROFILER_DRAWING
      end<for_each_feature>();
      LOG(LPROF, ("ForEachFeature=", metric<for_each_feature>(),
                  "FeatureCount=", metric<feature_count>(),
                  "TextureUpload= ", metric<yg_upload_data>()));
#endif
    }
    catch (redraw_operation_cancelled const &)
    {
      m_renderQueue.renderStatePtr()->m_isEmptyModelCurrent = false;
      m_renderQueue.renderStatePtr()->m_isEmptyModelActual = false;
    }

    if (m_navigator.Update(m_timer.ElapsedSeconds()))
      Invalidate();
  }

  /// Function for calling from platform dependent-paint function.
  template <typename TModel>
  void FrameWork<TModel>::Paint(shared_ptr<PaintEvent> e)
  {
    // Making a copy of actualFrameInfo to compare without synchronizing.
    //typename yg::gl::RenderState state = m_renderQueue.CopyState();

    DrawerYG * pDrawer = e->drawer().get();

    m_informationDisplay.setScreen(m_navigator.Screen());

    m_informationDisplay.setDebugInfo(m_renderQueue.renderState().m_duration, my::rounds(GetCurrentScale()));

    m_informationDisplay.enableRuler(!IsEmptyModel());

    m2::PointD const center = m_navigator.Screen().ClipRect().Center();

    m_informationDisplay.setGlobalRect(m_navigator.Screen().GlobalRect());
    m_informationDisplay.setCenter(m2::PointD(MercatorBounds::XToLon(center.x), MercatorBounds::YToLat(center.y)));

    {
      threads::MutexGuard guard(*m_renderQueue.renderState().m_mutex.get());

      if (m_isBenchmarking)
      {
        m2::PointD const center = m_renderQueue.renderState().m_actualScreen.ClipRect().Center();
        m_informationDisplay.setScreen(m_renderQueue.renderState().m_actualScreen);
        m_informationDisplay.setCenter(m2::PointD(MercatorBounds::XToLon(center.x), MercatorBounds::YToLat(center.y)));

        if (!m_isBenchmarkInitialized)
        {
          e->drawer()->screen()->beginFrame();
          e->drawer()->screen()->clear(m_bgColor);
          m_informationDisplay.setDisplayRect(m2::RectI(0, 0, 100, 100));
          m_informationDisplay.enableRuler(false);
          m_informationDisplay.doDraw(e->drawer().get());
          e->drawer()->screen()->endFrame();
        }
      }

      if (m_renderQueue.renderState().m_actualTarget.get() != 0)
      {
        e->drawer()->screen()->beginFrame();
        e->drawer()->screen()->clear(m_bgColor);

        m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(false);

        OGLCHECK(glMatrixMode(GL_MODELVIEW));
        OGLCHECK(glPushMatrix());
        OGLCHECK(glTranslatef(-ptShift.x, -ptShift.y, 0));

        ScreenBase currentScreen = m_navigator.Screen();

        m_informationDisplay.enableEmptyModelMessage(m_renderQueue.renderStatePtr()->m_isEmptyModelActual);

        if (m_isBenchmarking)
          currentScreen = m_renderQueue.renderState().m_actualScreen;

        pDrawer->screen()->blit(m_renderQueue.renderState().m_actualTarget,
                                m_renderQueue.renderState().m_actualScreen,
                                currentScreen);

/*        m_tiler.seed(currentScreen, m_tileSize);

        while (m_tiler.hasTile())
        {
          yg::Tiler::RectInfo ri = m_tiler.nextTile();

          m_renderQueue.tileCache().lock();
          if (m_renderQueue.tileCache().hasTile(ri))
          {
            yg::Tile tile = m_renderQueue.tileCache().getTile(ri);
            m2::RectD pxRect;
            currentScreen.GtoP(ri.m_rect, pxRect);

            pDrawer->screen()->drawRectangle(pxRect, yg::Color(255, 0, 0, 64), yg::maxDepth - 1);

            m_renderQueue.tileCache().unlock();
//            pDrawer->screen()->blit(tile.m_renderTarget, tile.m_tileScreen, currentScreen);
          }
          else
          {
            m_renderQueue.tileCache().unlock();
//            m_renderQueue.addTileRenderCmd();
            m2::RectD pxRect;
            currentScreen.GtoP(ri.m_rect, pxRect);
            pDrawer->screen()->drawRectangle(pxRect, yg::Color(0, 0, 255, 192 - (ri.m_distance * 3 > 255 ? 255 : ri.m_distance * 3) / (255.0 / 192)), yg::maxDepth - 2);
          }
        }
*/

        m_informationDisplay.doDraw(pDrawer);

/*        m_renderQueue.renderState().m_actualInfoLayer->draw(
              pDrawer->screen().get(),
              m_renderQueue.renderState().m_actualScreen.PtoGMatrix() * currentScreen.GtoPMatrix());*/

        m_locationState.DrawMyPosition(*pDrawer, m_navigator.Screen());

        e->drawer()->screen()->endFrame();

        OGLCHECK(glPopMatrix());
      }
      else
      {
        e->drawer()->screen()->beginFrame();
        e->drawer()->screen()->clear(m_bgColor);
        e->drawer()->screen()->endFrame();
      }
    }
  }

  template <typename TModel>
  void FrameWork<TModel>::CenterViewport(m2::PointD const & pt)
  {
    m_navigator.CenterViewport(pt);
    UpdateNow();
  }

  int const theMetersFactor = 6;

  template <typename TModel>
  void FrameWork<TModel>::ShowRect(m2::RectD rect)
  {
    double const minSizeX = MercatorBounds::ConvertMetresToX(rect.minX(), theMetersFactor * m_metresMinWidth);
    double const minSizeY = MercatorBounds::ConvertMetresToY(rect.minY(), theMetersFactor * m_metresMinWidth);
    if (rect.SizeX() < minSizeX && rect.SizeY() < minSizeY)
      rect.SetSizes(minSizeX, minSizeY);

    m_navigator.SetFromRect(rect);
    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::MemoryWarning()
  {
    // clearing caches on memory warning.
    m_model.ClearCaches();
    LOG(LINFO, ("MemoryWarning"));
  }

  template <typename TModel>
  void FrameWork<TModel>::EnterBackground()
  {
    // clearing caches on entering background.
    m_model.ClearCaches();
  }

  template <typename TModel>
  void FrameWork<TModel>::EnterForeground()
  {
  }

  /// @TODO refactor to accept point and min visible length
  template <typename TModel>
  void FrameWork<TModel>::CenterAndScaleViewport()
  {
    m2::PointD const pt = m_locationState.Position();
    m_navigator.CenterViewport(pt);

    m2::RectD clipRect = m_navigator.Screen().ClipRect();

    double const xMinSize = theMetersFactor * max(m_locationState.ErrorRadius(),
                              MercatorBounds::ConvertMetresToX(pt.x, m_metresMinWidth));
    double const yMinSize = theMetersFactor * max(m_locationState.ErrorRadius(),
                              MercatorBounds::ConvertMetresToY(pt.y, m_metresMinWidth));

    bool needToScale = false;

    if (clipRect.SizeX() < clipRect.SizeY())
      needToScale = clipRect.SizeX() > xMinSize * 3;
    else
      needToScale = clipRect.SizeY() > yMinSize * 3;

    //if ((ClipRect.SizeX() < 3 * errorRadius) || (ClipRect.SizeY() < 3 * errorRadius))
    //  needToScale = true;

    if (needToScale)
    {
      double const k = max(xMinSize / clipRect.SizeX(),
                     yMinSize / clipRect.SizeY());

      clipRect.Scale(k);
      m_navigator.SetFromRect(clipRect);
    }

    UpdateNow();
  }

  /// Show all model by it's world rect.
  template <typename TModel>
  void FrameWork<TModel>::ShowAll()
  {
    SetMaxWorldRect();
    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::Repaint()
  {
    m_renderQueue.SetRedrawAll();
    AddRedrawCommandSure();
    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::RepaintRect(m2::RectD const & rect)
  {
    threads::MutexGuard lock(*m_renderQueue.renderState().m_mutex.get());
    m2::RectD pxRect(0, 0, m_renderQueue.renderState().m_surfaceWidth, m_renderQueue.renderState().m_surfaceHeight);
    m2::RectD glbRect;
    m_navigator.Screen().PtoG(pxRect, glbRect);
    if (glbRect.Intersect(rect))
      Repaint();
  }

  /// @name Drag implementation.
  //@{
  template <typename TModel>
  void FrameWork<TModel>::StartDrag(DragEvent const & e)
  {
    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);
    m2::PointD pos = m_navigator.OrientPoint(e.Pos()) + ptShift;
    m_navigator.StartDrag(pos, m_timer.ElapsedSeconds());

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, pos);
#endif

    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::DoDrag(DragEvent const & e)
  {
    m_centeringMode = EDoNothing;

    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m2::PointD pos = m_navigator.OrientPoint(e.Pos()) + ptShift;
    m_navigator.DoDrag(pos, m_timer.ElapsedSeconds());

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, pos);
#endif

    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::StopDrag(DragEvent const & e)
  {
    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m2::PointD pos = m_navigator.OrientPoint(e.Pos()) + ptShift;

    m_navigator.StopDrag(pos, m_timer.ElapsedSeconds(), true);

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, m2::PointD(0, 0));
#endif

    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::Move(double azDir, double factor)
  {
    m_navigator.Move(azDir, factor);
//    m_tiler.seed(m_navigator.Screen(), m_tileSize);
    UpdateNow();
  }
  //@}

  /// @name Scaling.
  //@{
  template <typename TModel>
  void FrameWork<TModel>::ScaleToPoint(ScaleToPointEvent const & e)
  {
    m2::PointD const pt = (m_centeringMode == EDoNothing)
        ? m_navigator.OrientPoint(e.Pt()) + m_renderQueue.renderState().coordSystemShift(true)
        : m_navigator.Screen().PixelRect().Center();

    m_navigator.ScaleToPoint(pt, e.ScaleFactor(), m_timer.ElapsedSeconds());

    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::ScaleDefault(bool enlarge)
  {
    Scale(enlarge ? 1.5 : 2.0/3.0);
  }

  template <typename TModel>
  void FrameWork<TModel>::Scale(double scale)
  {
    m_navigator.Scale(scale);
//    m_tiler.seed(m_navigator.Screen(), m_tileSize);
    UpdateNow();
  }

  template <typename TModel>
  void FrameWork<TModel>::StartScale(ScaleEvent const & e)
  {
    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m2::PointD pt1 = m_navigator.OrientPoint(e.Pt1()) + ptShift;
    m2::PointD pt2 = m_navigator.OrientPoint(e.Pt2()) + ptShift;

    if ((m_locationState & location::State::EGps) && (m_centeringMode == ECenterOnly))
    {
      m2::PointD ptC = (pt1 + pt2) / 2;
      m2::PointD ptDiff = m_navigator.Screen().PixelRect().Center() - ptC;
      pt1 += ptDiff;
      pt2 += ptDiff;
    }

    m_navigator.StartScale(pt1, pt2, m_timer.ElapsedSeconds());

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, pt1);
    m_informationDisplay.setDebugPoint(1, pt2);
#endif

    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::DoScale(ScaleEvent const & e)
  {
    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m2::PointD pt1 = m_navigator.OrientPoint(e.Pt1()) + ptShift;
    m2::PointD pt2 = m_navigator.OrientPoint(e.Pt2()) + ptShift;

    if ((m_locationState & location::State::EGps) && (m_centeringMode == ECenterOnly))
    {
      m2::PointD ptC = (pt1 + pt2) / 2;
      m2::PointD ptDiff = m_navigator.Screen().PixelRect().Center() - ptC;
      pt1 += ptDiff;
      pt2 += ptDiff;
    }

    m_navigator.DoScale(pt1, pt2, m_timer.ElapsedSeconds());

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, pt1);
    m_informationDisplay.setDebugPoint(1, pt2);
#endif

    Invalidate();
  }

  template <typename TModel>
  void FrameWork<TModel>::StopScale(ScaleEvent const & e)
  {
    m2::PointD ptShift = m_renderQueue.renderState().coordSystemShift(true);

    m2::PointD pt1 = m_navigator.OrientPoint(e.Pt1()) + ptShift;
    m2::PointD pt2 = m_navigator.OrientPoint(e.Pt2()) + ptShift;

    if ((m_locationState & location::State::EGps) && (m_centeringMode == ECenterOnly))
    {
      m2::PointD ptC = (pt1 + pt2) / 2;
      m2::PointD ptDiff = m_navigator.Screen().PixelRect().Center() - ptC;
      pt1 += ptDiff;
      pt2 += ptDiff;
    }

    m_navigator.StopScale(pt1, pt2, m_timer.ElapsedSeconds());

#ifdef DRAW_TOUCH_POINTS
    m_informationDisplay.setDebugPoint(0, m2::PointD(0, 0));
    m_informationDisplay.setDebugPoint(0, m2::PointD(0, 0));
#endif

    UpdateNow();
  }

  template<typename TModel>
  void FrameWork<TModel>::Search(string const & text, SearchCallbackT callback)
  {
    threads::MutexGuard lock(m_modelSyn);

    if (!m_pSearchEngine.get())
    {
      search::CategoriesHolder holder;
      string buffer;
      ReaderT(GetPlatform().GetReader(SEARCH_CATEGORIES_FILE_NAME)).ReadAsString(buffer);
      holder.LoadFromStream(buffer);
      m_pSearchEngine.reset(new search::Engine(&m_model.GetIndex(), holder));
    }

    m_pSearchEngine->Search(text, m_navigator.Screen().GlobalRect(), callback);
  }

template class FrameWork<model::FeaturesFetcher>;