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