Remove other level tiles when all current level tiles exists
[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(QString)),
67             this, SIGNAL(error(QString)));
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 void MapEngine::init()
246 {
247     qDebug() << __PRETTY_FUNCTION__;
248
249     QPointF startLocation;
250     QSettings settings(DIRECTORY_NAME, FILE_NAME);
251
252     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
253         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
254         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
255
256         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
257         m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
258     } else {
259         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
260         startLocation = settings.value(MAP_LAST_POSITION,
261                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
262     }
263
264     emit zoomLevelChanged(m_zoomLevel);
265     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
266 }
267
268 bool MapEngine::isAutoCenteringEnabled()
269 {
270     return m_autoCenteringEnabled;
271 }
272
273 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
274 {
275     qDebug() << __PRETTY_FUNCTION__;
276
277     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
278     QPoint temp = m_centerTile;
279     m_centerTile = centerTile;
280
281     return (centerTile != temp);
282 }
283
284 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
285 {
286     qDebug() << __PRETTY_FUNCTION__;
287
288     // add normal tile inside the world
289     QPoint tileNumber(x, y);
290     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
291
292     // note: add 1 so odd width is rounded up and even is rounded down
293     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
294
295     // duplicate to east side? (don't need to duplicate over padding)
296     if (tileNumber.x() < (tilesGridWidthHalf - GRID_PADDING)) {
297         QPoint adjustedTileNumber(tileNumber.x() + tileMaxValue(zoomLevel) + 1, tileNumber.y());
298         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
299     }
300
301     // duplicate to west side? (don't need to duplicate over padding)
302     if (tileNumber.x() > (tileMaxValue(zoomLevel) - tilesGridWidthHalf + GRID_PADDING - 1)) {
303         QPoint adjustedTileNumber(tileNumber.x() - tileMaxValue(zoomLevel) - 1, tileNumber.y());
304         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
305     }
306 }
307
308 int MapEngine::normalize(int value, int min, int max)
309 {
310     qDebug() << __PRETTY_FUNCTION__;
311     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
312
313     while (value < min)
314         value += max - min + 1;
315
316     while (value > max)
317         value -= max - min + 1;
318
319     return value;
320 }
321
322 void MapEngine::receiveOwnLocation(User *user)
323 {
324     qDebug() << __PRETTY_FUNCTION__;
325
326     if(user) {
327         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
328         if (m_ownLocation->pos().toPoint() != newPosition) {
329             m_ownLocation->setPos(newPosition);
330         }
331
332         if (!m_ownLocation->isVisible())
333             m_ownLocation->show();
334     }
335     else {
336         m_ownLocation->hide();
337     }
338
339     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
340 }
341
342 QGraphicsScene* MapEngine::scene()
343 {
344     qDebug() << __PRETTY_FUNCTION__;
345
346     return m_mapScene;
347 }
348
349 void MapEngine::setAutoCentering(bool enabled)
350 {
351     m_autoCenteringEnabled = enabled;
352 }
353
354 void MapEngine::setGPSEnabled(bool enabled)
355 {
356     m_gpsLocationItem->setEnabled(enabled);
357 }
358
359 void MapEngine::setLocation(QPoint sceneCoordinate)
360 {
361     qDebug() << __PRETTY_FUNCTION__;
362
363     // jump to opposite side of the world if world limit is exceeded
364     if (sceneCoordinate.x() < MAP_MIN_PIXEL_X)
365         sceneCoordinate.setX(sceneCoordinate.x() + MAP_PIXELS_X);
366     else if (sceneCoordinate.x() > MAP_MAX_PIXEL_X)
367         sceneCoordinate.setX(sceneCoordinate.x() - MAP_PIXELS_X);
368
369     if (disableAutoCentering(sceneCoordinate))
370         emit mapScrolledManually();
371
372     m_sceneCoordinate = sceneCoordinate;
373     emit locationChanged(m_sceneCoordinate);
374
375     if (isCenterTileChanged(sceneCoordinate)) {
376         getTiles(sceneCoordinate);
377         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
378     }
379
380     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
381 }
382
383 void MapEngine::setZoomLevel(int newZoomLevel)
384 {
385     qDebug() << __PRETTY_FUNCTION__;
386
387     m_zoomLevel = newZoomLevel;
388     zoomed();
389 }
390
391 void MapEngine::setTilesGridSize(const QSize &viewSize)
392 {
393     qDebug() << __PRETTY_FUNCTION__;
394
395     // there must be scrolling reserve of at least half tile added to tile amount
396     // calculated from view size
397     const qreal SCROLLING_RESERVE = 0.5;
398
399     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
400     const int CENTER_TILE_INACCURACY = 1;
401
402     int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
403                     + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
404     int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
405                      + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
406
407     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
408
409     m_tilesGridSize.setHeight(gridHeight);
410     m_tilesGridSize.setWidth(gridWidth);
411
412     qWarning() << __PRETTY_FUNCTION__ << "tiles:" << m_tilesGridSize.width()
413                                       << "*" << m_tilesGridSize.height()
414                                       << "=" << m_tilesGridSize.width() * m_tilesGridSize.height();
415 }
416
417 void MapEngine::setViewLocation(QPointF latLonCoordinate)
418 {
419     qDebug() << __PRETTY_FUNCTION__;
420
421     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
422
423     m_lastManualPosition = sceneCoordinate;
424
425     setLocation(sceneCoordinate);
426 }
427
428 int MapEngine::tileMaxValue(int zoomLevel)
429 {
430     qDebug() << __PRETTY_FUNCTION__;
431
432     return (1 << zoomLevel) - 1;
433 }
434
435 QString MapEngine::tilePath(int zoomLevel, int x, int y)
436 {
437     qDebug() << __PRETTY_FUNCTION__;
438
439     QString tilePathString(QString::number(zoomLevel) + "/");
440     tilePathString.append(QString::number(x) + "/");
441     tilePathString.append(QString::number(y));
442
443     return tilePathString;
444 }
445
446 void MapEngine::updateViewTilesSceneRect()
447 {
448     qDebug() << __PRETTY_FUNCTION__;
449
450     const QPoint ONE_TILE = QPoint(1, 1);
451     const QPoint ONE_PIXEL = QPoint(1, 1);
452
453     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
454     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
455     // of the last tile.
456     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
457                                                             m_viewTilesGrid.bottomRight()
458                                                              + ONE_TILE) - ONE_PIXEL;
459
460     m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
461 }
462
463 void MapEngine::viewResized(const QSize &size)
464 {
465     qDebug() << __PRETTY_FUNCTION__;
466
467     m_viewSize = size;
468     setTilesGridSize(m_viewSize);
469
470     emit locationChanged(m_sceneCoordinate);
471     getTiles(m_sceneCoordinate);
472     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
473     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
474 }
475
476 void MapEngine::viewZoomFinished()
477 {
478     qDebug() << __PRETTY_FUNCTION__;
479
480     if (m_zoomedIn) {
481         m_zoomedIn = false;
482         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
483     }
484
485     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
486         emit maxZoomLevelReached();
487     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
488         emit minZoomLevelReached();
489
490     m_mapScene->setZoomLevel(m_zoomLevel);
491 }
492
493 void MapEngine::zoomed()
494 {
495     emit zoomLevelChanged(m_zoomLevel);
496     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
497     getTiles(m_sceneCoordinate);
498     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
499     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
500 }
501
502 void MapEngine::zoomIn()
503 {
504     qDebug() << __PRETTY_FUNCTION__;
505
506     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
507         m_zoomLevel++;
508         m_zoomedIn = true;
509         zoomed();
510     }
511 }
512
513 void MapEngine::zoomOut()
514 {
515     qDebug() << __PRETTY_FUNCTION__;
516
517     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
518         m_zoomLevel--;
519         zoomed();
520     }
521 }