Finished basic map scale feature
[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 "ownlocationitem.h"
42
43 #include "mapengine.h"
44 #include "network/networkaccessmanager.h"
45
46 MapEngine::MapEngine(QObject *parent)
47     : QObject(parent),
48       m_autoCenteringEnabled(false),
49       m_zoomedIn(false),
50       m_zoomLevel(DEFAULT_ZOOM_LEVEL),
51       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
52       m_lastManualPosition(QPoint(0, 0)),
53       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
54 {
55     qDebug() << __PRETTY_FUNCTION__;
56
57     m_mapScene = new MapScene(this);
58
59     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
60     connect(this, SIGNAL(fetchImage(int, int, int)),
61             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
62     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
63             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
64     connect(m_mapFetcher, SIGNAL(error(QString)),
65             this, SIGNAL(error(QString)));
66
67     m_ownLocation = new OwnLocationItem();
68     m_ownLocation->hide(); // hide until first location info is received
69     m_mapScene->addItem(m_ownLocation);
70
71     m_gpsLocationItem = new GPSLocationItem();
72     m_mapScene->addItem(m_gpsLocationItem);
73
74     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
75     connect(this, SIGNAL(zoomLevelChanged(int)),
76             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
77
78     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
79             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
80
81     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
82             this, SIGNAL(locationItemClicked(QList<QString>)));
83 }
84
85 MapEngine::~MapEngine()
86 {
87     qDebug() << __PRETTY_FUNCTION__;
88
89     QSettings settings(DIRECTORY_NAME, FILE_NAME);
90     settings.setValue(MAP_LAST_POSITION,
91                       convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
92     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
93 }
94
95 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
96 {
97     qDebug() << __PRETTY_FUNCTION__;
98
99     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
100     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
101     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
102     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
103     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
104
105     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
106
107     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
108 }
109
110 QPointF MapEngine::centerGeoCoordinate()
111 {
112     qDebug() << __PRETTY_FUNCTION__;
113
114     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
115 }
116
117 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
118 {
119     qDebug() << __PRETTY_FUNCTION__;
120
121     qreal longitude = latLonCoordinate.x();
122     qreal latitude = latLonCoordinate.y();
123
124     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
125         return QPoint(UNDEFINED, UNDEFINED);
126     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
127         return QPoint(UNDEFINED, UNDEFINED);
128
129     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
130
131     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
132     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
133                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
134
135     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
136 }
137
138 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
139 {
140     qDebug() << __PRETTY_FUNCTION__;
141
142     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
143     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
144     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
145
146     tileFactor = 1 << zoomLevel;
147     double longitude = xFactor / tileFactor * 360.0 - 180;
148
149     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
150     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
151
152     return QPointF(longitude, latitude);
153 }
154
155 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
156 {
157     qDebug() << __PRETTY_FUNCTION__;
158
159     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
160     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
161     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
162
163     return QPoint(x, y);
164 }
165
166 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
167 {
168     qDebug() << __PRETTY_FUNCTION__;
169
170     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
171     int x = tileNumber.x() * TILE_SIZE_X * pow;
172     int y = tileNumber.y() * TILE_SIZE_Y * pow;
173
174     return QPoint(x, y);
175 }
176
177 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
178 {
179     if (isAutoCenteringEnabled()) {
180         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
181
182         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
183                                       m_lastManualPosition.y() / zoomFactor);
184
185         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
186                                       sceneCoordinate.y() / zoomFactor);
187
188         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
189             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
190             return true;
191     }
192
193     return false;
194 }
195
196 void MapEngine::getTiles(QPoint sceneCoordinate)
197 {
198     qDebug() << __PRETTY_FUNCTION__;
199
200     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
201     updateViewTilesSceneRect();
202
203     int topLeftX = m_viewTilesGrid.topLeft().x();
204     int topLeftY = m_viewTilesGrid.topLeft().y();
205     int bottomRightX = m_viewTilesGrid.bottomRight().x();
206     int bottomRightY = m_viewTilesGrid.bottomRight().y();
207
208     int tileMaxVal = tileMaxValue(m_zoomLevel);
209
210     for (int x = topLeftX; x <= bottomRightX; ++x) {
211         for (int y = topLeftY; y <= bottomRightY; ++y) {
212
213             int tileX = x;
214             int tileY = y;
215
216             if (tileX < 0)
217                 tileX += tileMaxVal;
218             else if (tileX > tileMaxVal)
219                 tileX -= tileMaxVal;
220
221             if (tileY < 0)
222                 tileY += tileMaxVal;
223             else if (tileY > tileMaxVal)
224                 tileY -= tileMaxVal;
225
226             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
227                 emit fetchImage(m_zoomLevel, tileX, tileY);
228         }
229     }
230 }
231
232 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
233 {
234     qDebug() << __PRETTY_FUNCTION__;
235
236     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
237
238     if (m_autoCenteringEnabled)
239         setViewLocation(position);
240 }
241
242 void MapEngine::init()
243 {
244     qDebug() << __PRETTY_FUNCTION__;
245
246     QPointF startLocation;
247     QSettings settings(DIRECTORY_NAME, FILE_NAME);
248
249     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
250         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
251         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
252
253         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
254         m_zoomLevel = DEFAULT_START_ZOOM_LEVEL;
255     } else {
256         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
257         startLocation = settings.value(MAP_LAST_POSITION,
258                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
259     }
260
261     emit zoomLevelChanged(m_zoomLevel);
262     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
263 }
264
265 bool MapEngine::isAutoCenteringEnabled()
266 {
267     return m_autoCenteringEnabled;
268 }
269
270 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
271 {
272     qDebug() << __PRETTY_FUNCTION__;
273
274     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
275     QPoint temp = m_centerTile;
276     m_centerTile = centerTile;
277
278     return (centerTile != temp);
279 }
280
281 qreal MapEngine::sceneResolution()
282 {
283     qDebug() << __PRETTY_FUNCTION__;
284
285     const int SHIFT = 200;
286     const int KM_TO_M = 1000;
287     qreal scale = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
288     QPointF centerCoordinate = centerGeoCoordinate();
289     QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
290                                            , m_sceneCoordinate.y());
291     QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
292     qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
293     return (dist / SHIFT);
294 }
295
296 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
297 {
298     qDebug() << __PRETTY_FUNCTION__;
299
300     QString hashKey = tilePath(zoomLevel, x, y);
301     if (!m_mapScene->isTileInScene(hashKey)) {
302
303         MapTile *mapTile = new MapTile();
304         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
305         mapTile->setTileNumber(QPoint(x, y));
306         mapTile->setPixmap(image);
307
308         m_mapScene->addTile(mapTile, hashKey);
309
310         m_mapScene->enqueueRemoveStackedTiles(mapTile);
311    }
312 }
313
314 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
315 {
316     qDebug() << __PRETTY_FUNCTION__;
317
318     const qreal TORAD = (M_PI/180);
319
320     qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
321     qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
322     qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
323               * pow(sin(dLon/2),2);
324     qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
325
326     return (EARTH_RADIUS * c);
327 }
328
329 void MapEngine::receiveOwnLocation(User *user)
330 {
331     qDebug() << __PRETTY_FUNCTION__;
332
333     if(user) {
334         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
335         if (m_ownLocation->pos().toPoint() != newPosition) {
336             m_ownLocation->setPos(newPosition);
337         }
338
339         if (!m_ownLocation->isVisible())
340             m_ownLocation->show();
341     }
342     else {
343         m_ownLocation->hide();
344     }
345 }
346
347 QGraphicsScene* MapEngine::scene()
348 {
349     qDebug() << __PRETTY_FUNCTION__;
350
351     return m_mapScene;
352 }
353
354 void MapEngine::setAutoCentering(bool enabled)
355 {
356     m_autoCenteringEnabled = enabled;
357 }
358
359 void MapEngine::setGPSEnabled(bool enabled)
360 {
361     m_gpsLocationItem->setEnabled(enabled);
362 }
363
364 void MapEngine::setLocation(QPoint sceneCoordinate)
365 {
366     qDebug() << __PRETTY_FUNCTION__;
367
368     if (disableAutoCentering(sceneCoordinate))
369         emit mapScrolledManually();
370
371     m_sceneCoordinate = sceneCoordinate;
372     emit locationChanged(m_sceneCoordinate);
373
374     if (isCenterTileChanged(sceneCoordinate)) {
375         getTiles(sceneCoordinate);
376         m_mapScene->removeOutOfViewTiles();
377     }
378
379     emit newMapResolution(sceneResolution());
380 }
381
382 void MapEngine::setZoomLevel(int newZoomLevel)
383 {
384     qDebug() << __PRETTY_FUNCTION__;
385
386     m_zoomLevel = newZoomLevel;
387     emit zoomLevelChanged(m_zoomLevel);
388 }
389
390 void MapEngine::setViewLocation(QPointF latLonCoordinate)
391 {
392     qDebug() << __PRETTY_FUNCTION__;
393
394     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
395
396     m_lastManualPosition = sceneCoordinate;
397
398     setLocation(sceneCoordinate);
399 }
400
401 int MapEngine::tileMaxValue(int zoomLevel)
402 {
403     qDebug() << __PRETTY_FUNCTION__;
404
405     return (1 << zoomLevel) - 1;
406 }
407
408 QString MapEngine::tilePath(int zoomLevel, int x, int y)
409 {
410     qDebug() << __PRETTY_FUNCTION__;
411
412     QString tilePathString(QString::number(zoomLevel) + "/");
413     tilePathString.append(QString::number(x) + "/");
414     tilePathString.append(QString::number(y));
415
416     return tilePathString;
417 }
418
419 void MapEngine::updateViewTilesSceneRect()
420 {
421     qDebug() << __PRETTY_FUNCTION__;
422
423     const QPoint ONE_TILE = QPoint(1, 1);
424     const QPoint ONE_PIXEL = QPoint(1, 1);
425
426     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
427     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
428     // of the last tile.
429     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
430                                                             m_viewTilesGrid.bottomRight()
431                                                              + ONE_TILE) - ONE_PIXEL;
432
433     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
434 }
435
436 void MapEngine::viewResized(const QSize &size)
437 {
438     qDebug() << __PRETTY_FUNCTION__;
439
440     m_viewSize = size;
441     emit locationChanged(m_sceneCoordinate);
442     getTiles(m_sceneCoordinate);
443     m_mapScene->removeOutOfViewTiles();
444 }
445
446 void MapEngine::viewZoomFinished()
447 {
448     qDebug() << __PRETTY_FUNCTION__;
449
450     if (m_zoomedIn) {
451         m_zoomedIn = false;
452         m_mapScene->removeOutOfViewTiles();
453     }
454
455     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
456         emit maxZoomLevelReached();
457     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
458         emit minZoomLevelReached();
459
460     emit newMapResolution(sceneResolution());
461 }
462
463 void MapEngine::zoomIn()
464 {
465     qDebug() << __PRETTY_FUNCTION__;
466
467     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
468         m_zoomLevel++;
469         m_zoomedIn = true;
470         emit zoomLevelChanged(m_zoomLevel);
471
472         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
473
474         getTiles(m_sceneCoordinate);
475     }
476 }
477
478 void MapEngine::zoomOut()
479 {
480     qDebug() << __PRETTY_FUNCTION__;
481
482     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
483         m_zoomLevel--;
484         emit zoomLevelChanged(m_zoomLevel);
485
486         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
487
488         getTiles(m_sceneCoordinate);
489     }
490 }