Jump to opposite side of the world
[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 <QNetworkAccessManager>
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 "maptile.h"
42 #include "ownlocationitem.h"
43
44 #include "mapengine.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(new QNetworkAccessManager(this), 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
65     m_ownLocation = new OwnLocationItem();
66     m_ownLocation->hide(); // hide until first location info is received
67     m_mapScene->addItem(m_ownLocation);
68
69     m_gpsLocationItem = new GPSLocationItem();
70     m_mapScene->addItem(m_gpsLocationItem);
71
72     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
73     connect(this, SIGNAL(zoomLevelChanged(int)),
74             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
75
76     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
77             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
78
79     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
80             this, SIGNAL(locationItemClicked(QList<QString>)));
81 }
82
83 MapEngine::~MapEngine()
84 {
85     qDebug() << __PRETTY_FUNCTION__;
86
87     QSettings settings(DIRECTORY_NAME, FILE_NAME);
88     settings.setValue(MAP_LAST_POSITION,
89                       convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
90     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
91 }
92
93 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
98     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
99     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
100     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
101     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
102
103     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
104
105 //    qWarning() << __PRETTY_FUNCTION__ << topLeftX << topLeftY << 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     qWarning() << __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 //    qWarning() << __PRETTY_FUNCTION__ << "topleft:" << topLeftX << topLeftY
211 //                                      << "bottomright:" << bottomRightX << bottomRightY;
212
213     for (int x = topLeftX; x <= bottomRightX; ++x) {
214         for (int y = topLeftY; y <= bottomRightY; ++y) {
215
216             int tileX = x;
217             int tileY = y;
218
219             int debugX = x;
220
221             if (tileX < 0)
222                 tileX += tileMaxVal + 1;
223             else if (tileX > tileMaxVal)
224                 tileX -= tileMaxVal + 1;
225
226             if (tileY < 0)
227                 tileY += tileMaxVal + 1;
228             else if (tileY > tileMaxVal)
229                 tileY -= tileMaxVal + 1;
230
231             qWarning() << __PRETTY_FUNCTION__ << "x value:" << debugX << "->" << tileX;
232
233             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
234                 emit fetchImage(m_zoomLevel, tileX, tileY);
235         }
236     }
237 }
238
239 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
240 {
241     qDebug() << __PRETTY_FUNCTION__;
242
243     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
244
245     if (m_autoCenteringEnabled)
246         setViewLocation(position);
247 }
248
249 void MapEngine::init()
250 {
251     qDebug() << __PRETTY_FUNCTION__;
252
253     QPointF startLocation;
254     QSettings settings(DIRECTORY_NAME, FILE_NAME);
255
256     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() ==
257         ERROR_VALUE_NOT_FOUND_ON_SETTINGS ||
258         settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() ==
259         ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
260
261         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
262         m_zoomLevel = DEFAULT_START_ZOOM_LEVEL;
263     }
264
265     else {
266         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
267         startLocation = settings.value(MAP_LAST_POSITION,
268                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
269     }
270
271     emit zoomLevelChanged(m_zoomLevel);
272     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
273 }
274
275 bool MapEngine::isAutoCenteringEnabled()
276 {
277     return m_autoCenteringEnabled;
278 }
279
280 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
281 {
282     qDebug() << __PRETTY_FUNCTION__;
283
284     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
285     QPoint temp = m_centerTile;
286     m_centerTile = centerTile;
287
288     return (centerTile != temp);
289 }
290
291 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
292 {
293     qDebug() << __PRETTY_FUNCTION__;
294
295     QString hashKey = tilePath(zoomLevel, x, y);
296     if (!m_mapScene->isTileInScene(hashKey)) {
297
298         MapTile *mapTile = new MapTile();
299         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
300         mapTile->setTileNumber(QPoint(x, y));
301         mapTile->setPixmap(image);
302
303         m_mapScene->addTile(mapTile, hashKey);
304
305         m_mapScene->enqueueRemoveStackedTiles(mapTile);
306    }
307 }
308
309 void MapEngine::receiveOwnLocation(User *user)
310 {
311     qDebug() << __PRETTY_FUNCTION__;
312
313     if(user) {
314         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
315         if (m_ownLocation->pos().toPoint() != newPosition) {
316             m_ownLocation->setPos(newPosition);
317         }
318
319         if (!m_ownLocation->isVisible())
320             m_ownLocation->show();
321     }
322     else {
323         m_ownLocation->hide();
324     }
325 }
326
327 QGraphicsScene* MapEngine::scene()
328 {
329     qDebug() << __PRETTY_FUNCTION__;
330
331     return m_mapScene;
332 }
333
334 void MapEngine::setAutoCentering(bool enabled)
335 {
336     m_autoCenteringEnabled = enabled;
337 }
338
339 void MapEngine::setGPSEnabled(bool enabled)
340 {
341     m_gpsLocationItem->setEnabled(enabled);
342 }
343
344 void MapEngine::setLocation(QPoint sceneCoordinate)
345 {
346     qDebug() << __PRETTY_FUNCTION__;
347
348     if (sceneCoordinate.x() < 0) {
349         qWarning() << __PRETTY_FUNCTION__ << "World west limit reached";
350         sceneCoordinate.setX(sceneCoordinate.x() + WORLD_PIXELS_X);
351     }
352     else if (sceneCoordinate.x() > WORLD_PIXELS_X - 1) {
353         qWarning() << __PRETTY_FUNCTION__ << "World east limit reached";
354         sceneCoordinate.setX(sceneCoordinate.x() - WORLD_PIXELS_X);
355     }
356
357     if (disableAutoCentering(sceneCoordinate))
358         emit mapScrolledManually();
359
360     m_sceneCoordinate = sceneCoordinate;
361     emit locationChanged(m_sceneCoordinate);
362
363     if (isCenterTileChanged(sceneCoordinate)) {
364         getTiles(sceneCoordinate);
365         m_mapScene->removeOutOfViewTiles();
366     }
367 }
368
369 void MapEngine::setViewLocation(QPointF latLonCoordinate)
370 {
371     qDebug() << __PRETTY_FUNCTION__;
372
373     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
374
375     m_lastManualPosition = sceneCoordinate;
376
377     setLocation(sceneCoordinate);
378 }
379
380 int MapEngine::tileMaxValue(int zoomLevel)
381 {
382     qDebug() << __PRETTY_FUNCTION__;
383
384     return (1 << zoomLevel) - 1;
385 }
386
387 QString MapEngine::tilePath(int zoomLevel, int x, int y)
388 {
389     qDebug() << __PRETTY_FUNCTION__;
390
391     QString tilePathString(QString::number(zoomLevel) + "/");
392     tilePathString.append(QString::number(x) + "/");
393     tilePathString.append(QString::number(y));
394
395     return tilePathString;
396 }
397
398 void MapEngine::updateViewTilesSceneRect()
399 {
400     qDebug() << __PRETTY_FUNCTION__;
401
402     const QPoint ONE_TILE = QPoint(1, 1);
403     const QPoint ONE_PIXEL = QPoint(1, 1);
404
405     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
406     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
407     // of the last tile.
408     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
409                                                             m_viewTilesGrid.bottomRight()
410                                                              + ONE_TILE) - ONE_PIXEL;
411
412     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
413 }
414
415 void MapEngine::viewResized(const QSize &size)
416 {
417     qDebug() << __PRETTY_FUNCTION__;
418
419     m_viewSize = size;
420     emit locationChanged(m_sceneCoordinate);
421     getTiles(m_sceneCoordinate);
422     m_mapScene->removeOutOfViewTiles();
423 }
424
425 void MapEngine::viewZoomFinished()
426 {
427     qDebug() << __PRETTY_FUNCTION__;
428
429     if (m_zoomedIn) {
430         m_zoomedIn = false;
431         m_mapScene->removeOutOfViewTiles();
432     }
433
434     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
435         emit maxZoomLevelReached();
436     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
437         emit minZoomLevelReached();
438 }
439
440 void MapEngine::zoomIn()
441 {
442     qDebug() << __PRETTY_FUNCTION__;
443
444     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
445         m_zoomLevel++;
446         m_zoomedIn = true;
447         emit zoomLevelChanged(m_zoomLevel);
448
449         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
450
451         getTiles(m_sceneCoordinate);
452     }
453 }
454
455 void MapEngine::zoomOut()
456 {
457     qDebug() << __PRETTY_FUNCTION__;
458
459     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
460         m_zoomLevel--;
461         emit zoomLevelChanged(m_zoomLevel);
462
463         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
464
465         getTiles(m_sceneCoordinate);
466     }
467 }