aa4ebe08cc50f7acfc7e21bb6e8bdbbb49582dfa
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8        Ville Tiensuu - ville.tiensuu@ixonos.com
9        Henri Lampela - henri.lampela@ixonos.com
10
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtAlgorithms>
27 #include <QDebug>
28 #include <QString>
29 #include <QStringList>
30 #include <QUrl>
31 #include <QHash>
32 #include <QHashIterator>
33 #include <QRect>
34
35 #include "common.h"
36 #include "frienditemshandler.h"
37 #include "gpslocationitem.h"
38 #include "mapcommon.h"
39 #include "mapfetcher.h"
40 #include "mapscene.h"
41 #include "mapscroller.h"
42 #include "maptile.h"
43 #include "network/networkaccessmanager.h"
44 #include "ownlocationitem.h"
45 #include "user/user.h"
46
47 #include "mapengine.h"
48
49 const int SMOOTH_CENTERING_TIME_MS = 1000;
50
51 MapEngine::MapEngine(QObject *parent)
52     : QObject(parent),
53       m_autoCenteringEnabled(false),
54       m_scrollStartedByGps(false),
55       m_smoothScrollRunning(false),
56       m_zoomedIn(false),
57       m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
58       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
59       m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
60       m_tilesGridSize(QSize(0, 0)),
61       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
62 {
63     qDebug() << __PRETTY_FUNCTION__;
64
65     m_mapScene = new MapScene(this);
66
67     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
68     connect(this, SIGNAL(fetchImage(int, int, int)),
69             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
70     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
71             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
72     connect(m_mapFetcher, SIGNAL(error(int, int)),
73             this, SIGNAL(error(int, int)));
74
75     m_ownLocation = new OwnLocationItem();
76     m_ownLocation->hide(); // hide until first location info is received
77     m_mapScene->addItem(m_ownLocation);
78
79     m_gpsLocationItem = new GPSLocationItem();
80     m_mapScene->addItem(m_gpsLocationItem);
81
82     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
83     connect(this, SIGNAL(zoomLevelChanged(int)),
84             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
85
86     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
87             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
88
89     connect(this, SIGNAL(friendImageReady(User*)),
90             m_friendItemsHandler, SLOT(friendImageReady(User*)));
91
92     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
93             this, SLOT(friendsPositionsUpdated()));
94
95     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
96             this, SIGNAL(locationItemClicked(QList<QString>)));
97
98     m_scroller = &MapScroller::getInstance();
99
100     connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
101             this, SLOT(setCenterPosition(SceneCoordinate)));
102
103     connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
104             this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
105 }
106
107 MapEngine::~MapEngine()
108 {
109     qDebug() << __PRETTY_FUNCTION__;
110
111     QSettings settings(DIRECTORY_NAME, FILE_NAME);
112
113     settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
114     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
115 }
116
117 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
118 {
119     qDebug() << __PRETTY_FUNCTION__;
120
121     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
122
123     QPoint topLeft;
124     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
125     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
126
127     return QRect(topLeft, m_tilesGridSize);
128 }
129
130 GeoCoordinate MapEngine::centerGeoCoordinate()
131 {
132     qDebug() << __PRETTY_FUNCTION__;
133
134     return GeoCoordinate(m_sceneCoordinate);
135 }
136
137 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
138 {
139     qDebug() << __PRETTY_FUNCTION__;
140
141     scrollToPosition(SceneCoordinate(coordinate));
142 }
143
144 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
145 {
146     qDebug() << __PRETTY_FUNCTION__;
147
148     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
149     int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
150     int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
151
152     return QPoint(x, y);
153 }
154
155 SceneCoordinate MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
156 {
157     qDebug() << __PRETTY_FUNCTION__;
158
159     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
160     int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
161     int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
162
163     return SceneCoordinate(x, y);
164 }
165
166 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
167 {
168     if (isAutoCenteringEnabled()) {
169         int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
170
171         SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
172                                       m_lastAutomaticPosition.y() / zoomFactor);
173
174         SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
175                                       coordinate.y() / zoomFactor);
176
177         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
178             || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
179
180             emit mapScrolledManually();
181         }
182     }
183 }
184
185 void MapEngine::friendsPositionsUpdated()
186 {
187     qDebug() << __PRETTY_FUNCTION__;
188
189     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
190 }
191
192 void MapEngine::getTiles(SceneCoordinate coordinate)
193 {
194     qDebug() << __PRETTY_FUNCTION__;
195
196     m_viewTilesGrid = calculateTileGrid(coordinate);
197     updateViewTilesSceneRect();
198     m_mapScene->setTilesGrid(m_viewTilesGrid);
199
200     int topLeftX = m_viewTilesGrid.topLeft().x();
201     int topLeftY = m_viewTilesGrid.topLeft().y();
202     int bottomRightX = m_viewTilesGrid.bottomRight().x();
203     int bottomRightY = m_viewTilesGrid.bottomRight().y();
204
205     int tileMaxVal = tileMaxIndex(m_zoomLevel);
206
207     for (int x = topLeftX; x <= bottomRightX; ++x) {
208         for (int y = topLeftY; y <= bottomRightY; ++y) {
209
210             // map doesn't span in vertical direction, so y index must be inside the limits
211             if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
212                 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
213                     emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
214             }
215         }
216     }
217 }
218
219 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
220 {
221     qDebug() << __PRETTY_FUNCTION__;
222
223     m_gpsLocationItem->updatePosition(SceneCoordinate(position), accuracy);
224     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
225
226     if (m_autoCenteringEnabled) {
227         m_lastAutomaticPosition = SceneCoordinate(position);
228         m_scrollStartedByGps = true;
229         scrollToPosition(m_lastAutomaticPosition);
230     }
231 }
232
233 qreal MapEngine::greatCircleDistance(GeoCoordinate firstLocation, GeoCoordinate secondLocation)
234 {
235     qDebug() << __PRETTY_FUNCTION__;
236
237     const qreal TO_RAD = (M_PI / 180);
238
239     qreal dLat = (secondLocation.latitude() - firstLocation.latitude()) * TO_RAD;
240     qreal dLon = (secondLocation.longitude() - firstLocation.longitude()) * TO_RAD;
241     qreal a = pow(sin(dLat / 2), 2)
242               + cos(firstLocation.latitude() * TO_RAD)
243                 * cos(secondLocation.latitude() * TO_RAD)
244                 * pow(sin(dLon / 2), 2);
245     qreal c = 2 * atan2(sqrt(a), sqrt(1 - a));
246
247     return (EARTH_RADIUS * c);
248 }
249
250 void MapEngine::init()
251 {
252     qDebug() << __PRETTY_FUNCTION__;
253
254     QSettings settings(DIRECTORY_NAME, FILE_NAME);
255
256     // init can be only done if both values exists in the settings
257     if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
258         QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
259         QVariant location = settings.value(MAP_LAST_POSITION);
260
261         // also the init can be only done if we are able to convert variants into target data types
262         if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
263             m_zoomLevel = zoomLevel.toInt();
264             m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
265         }
266     }
267
268     // emit zoom level and center coordinate so that all parts of the map system gets initialized
269     // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
270     //       so that the default values set in the constructor are used
271     emit zoomLevelChanged(m_zoomLevel);
272     scrollToPosition(m_sceneCoordinate);
273 }
274
275 bool MapEngine::isAutoCenteringEnabled()
276 {
277     return m_autoCenteringEnabled;
278 }
279
280 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
281 {
282     qDebug() << __PRETTY_FUNCTION__;
283
284     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
285     QPoint temp = m_centerTile;
286     m_centerTile = centerTile;
287
288     return (centerTile != temp);
289 }
290
291 qreal MapEngine::sceneResolution()
292 {
293     qDebug() << __PRETTY_FUNCTION__;
294
295     const int SHIFT = 200;
296     const int KM_TO_M = 1000;
297     qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
298     GeoCoordinate centerCoordinate = centerGeoCoordinate();
299     SceneCoordinate shiftedSceneCoordinate(m_sceneCoordinate.x() + SHIFT * scale,
300                                            m_sceneCoordinate.y());
301     GeoCoordinate shiftedCoordinate(shiftedSceneCoordinate);
302     qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
303     return (dist / SHIFT);
304 }
305
306 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
307 {
308     qDebug() << __PRETTY_FUNCTION__;
309
310     // add normal tile inside the world
311     QPoint tileNumber(x, y);
312     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
313
314     // note: add 1 so odd width is rounded up and even is rounded down
315     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
316
317     // duplicate to east side? (don't need to duplicate over padding)
318     if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
319         QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
320         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
321     }
322
323     // duplicate to west side? (don't need to duplicate over padding)
324     if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
325         QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
326         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
327     }
328 }
329
330 int MapEngine::normalize(int value, int min, int max)
331 {
332     qDebug() << __PRETTY_FUNCTION__;
333     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
334
335     while (value < min)
336         value += max - min + 1;
337
338     while (value > max)
339         value -= max - min + 1;
340
341     return value;
342 }
343
344 void MapEngine::receiveOwnLocation(User *user)
345 {
346     qDebug() << __PRETTY_FUNCTION__;
347
348     if(user) {
349         m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
350         if (!m_ownLocation->isVisible())
351             m_ownLocation->show();
352     } else {
353         m_ownLocation->hide();
354     }
355
356     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
357 }
358
359 QGraphicsScene* MapEngine::scene()
360 {
361     qDebug() << __PRETTY_FUNCTION__;
362
363     return m_mapScene;
364 }
365
366 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
367 {
368     qDebug() << __PRETTY_FUNCTION__;
369
370     if (m_smoothScrollRunning
371         && newState != QAbstractAnimation::Running) {
372             m_smoothScrollRunning = false;
373
374             // don't disable auto centering if current animation was stopped by new update from GPS
375             if (!m_scrollStartedByGps)
376                 disableAutoCenteringIfRequired(m_sceneCoordinate);
377     }
378
379     m_scrollStartedByGps = false;
380 }
381
382 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
383 {
384     qDebug() << __PRETTY_FUNCTION__;
385
386     m_scroller->stop();
387     m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
388     m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
389     m_scroller->setStartValue(m_sceneCoordinate);
390     m_scroller->setEndValue(coordinate);
391     m_smoothScrollRunning = true;
392     m_scroller->start();
393 }
394
395 void MapEngine::setAutoCentering(bool enabled)
396 {
397     qDebug() << __PRETTY_FUNCTION__;
398
399     m_autoCenteringEnabled = enabled;
400 }
401
402 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
403 {
404     qDebug() << __PRETTY_FUNCTION__;
405
406     // jump to opposite side of the world if world horizontal limit is exceeded
407     coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
408
409     // don't allow vertical scene coordinates go out of the map
410     coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
411                               coordinate.y(),
412                               double(OSM_MAP_MAX_PIXEL_Y)));
413
414     if (!m_smoothScrollRunning)
415         disableAutoCenteringIfRequired(coordinate);
416
417     m_sceneCoordinate = coordinate;
418     emit locationChanged(m_sceneCoordinate);
419
420     if (isCenterTileChanged(coordinate)) {
421         getTiles(coordinate);
422         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
423     }
424
425     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
426     emit newMapResolution(sceneResolution());
427 }
428
429 void MapEngine::setGPSEnabled(bool enabled)
430 {
431     qDebug() << __PRETTY_FUNCTION__;
432
433     m_gpsLocationItem->setEnabled(enabled);
434 }
435
436 void MapEngine::setZoomLevel(int newZoomLevel)
437 {
438     qDebug() << __PRETTY_FUNCTION__;
439
440     m_zoomLevel = newZoomLevel;
441     zoomed();
442 }
443
444 void MapEngine::setTilesGridSize(const QSize &viewSize)
445 {
446     qDebug() << __PRETTY_FUNCTION__;
447
448     // there must be scrolling reserve of at least half tile added to tile amount
449     // calculated from view size
450     const qreal SCROLLING_RESERVE = 0.5;
451
452     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
453     const int CENTER_TILE_INACCURACY = 1;
454
455     int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
456                     + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
457     int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
458                      + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
459
460     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
461
462     m_tilesGridSize.setHeight(gridHeight);
463     m_tilesGridSize.setWidth(gridWidth);
464 }
465
466 int MapEngine::tileMaxIndex(int zoomLevel)
467 {
468     qDebug() << __PRETTY_FUNCTION__;
469
470     // subtract one because first tile index is zero
471     return tilesPerSide(zoomLevel) - 1;
472 }
473
474 QString MapEngine::tilePath(int zoomLevel, int x, int y)
475 {
476     qDebug() << __PRETTY_FUNCTION__;
477
478     QString tilePathString(QString::number(zoomLevel) + "/");
479     tilePathString.append(QString::number(x) + "/");
480     tilePathString.append(QString::number(y));
481
482     return tilePathString;
483 }
484
485 int MapEngine::tilesPerSide(int zoomLevel)
486 {
487     return (1 << zoomLevel);
488 }
489
490 void MapEngine::updateViewTilesSceneRect()
491 {
492     qDebug() << __PRETTY_FUNCTION__;
493
494     const QPoint ONE_TILE = QPoint(1, 1);
495     const double ONE_PIXEL = 1;
496
497     SceneCoordinate topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel,
498                                                         m_viewTilesGrid.topLeft());
499
500     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
501     // of the last tile.
502     SceneCoordinate bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
503                                                             m_viewTilesGrid.bottomRight()
504                                                              + ONE_TILE);
505     bottomRight.setX(bottomRight.x() - ONE_PIXEL);
506     bottomRight.setY(bottomRight.y() - ONE_PIXEL);
507
508     m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
509                                             bottomRight.toPointF().toPoint()));
510 }
511
512 void MapEngine::viewResized(const QSize &size)
513 {
514     qDebug() << __PRETTY_FUNCTION__;
515
516     m_viewSize = size;
517     setTilesGridSize(m_viewSize);
518
519     emit locationChanged(m_sceneCoordinate);
520     getTiles(m_sceneCoordinate);
521     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
522     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
523 }
524
525 void MapEngine::viewZoomFinished()
526 {
527     qDebug() << __PRETTY_FUNCTION__;
528
529     if (m_zoomedIn) {
530         m_zoomedIn = false;
531         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
532     }
533
534     if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
535         emit maxZoomLevelReached();
536     else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
537         emit minZoomLevelReached();
538 }
539
540 void MapEngine::zoomed()
541 {
542     emit zoomLevelChanged(m_zoomLevel);
543     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
544     m_mapScene->setZoomLevel(m_zoomLevel);
545     getTiles(m_sceneCoordinate);
546     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
547     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
548     emit newMapResolution(sceneResolution());
549 }
550
551 void MapEngine::zoomIn()
552 {
553     qDebug() << __PRETTY_FUNCTION__;
554
555     if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
556         m_zoomLevel++;
557         m_zoomedIn = true;
558         zoomed();
559     }
560 }
561
562 void MapEngine::zoomOut()
563 {
564     qDebug() << __PRETTY_FUNCTION__;
565
566     if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {
567         m_zoomLevel--;
568         zoomed();
569     }
570 }