Out of view tiles removal modified
[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
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
101     QPoint topLeft;
102     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
103     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
104
105     return QRect(topLeft, m_tilesGridSize);
106 }
107
108 QPointF MapEngine::centerGeoCoordinate()
109 {
110     qDebug() << __PRETTY_FUNCTION__;
111
112     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
113 }
114
115 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
116 {
117     qDebug() << __PRETTY_FUNCTION__;
118
119     qreal longitude = latLonCoordinate.x();
120     qreal latitude = latLonCoordinate.y();
121
122     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
123         return QPoint(UNDEFINED, UNDEFINED);
124     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
125         return QPoint(UNDEFINED, UNDEFINED);
126
127     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
128
129     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
130     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
131                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
132
133     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
134 }
135
136 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
137 {
138     qDebug() << __PRETTY_FUNCTION__;
139
140     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
141     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
142     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
143
144     tileFactor = 1 << zoomLevel;
145     double longitude = xFactor / tileFactor * 360.0 - 180;
146
147     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
148     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
149
150     return QPointF(longitude, latitude);
151 }
152
153 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
154 {
155     qDebug() << __PRETTY_FUNCTION__;
156
157     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
158     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
159     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
160
161     return QPoint(x, y);
162 }
163
164 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
165 {
166     qDebug() << __PRETTY_FUNCTION__;
167
168     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
169     int x = tileNumber.x() * TILE_SIZE_X * pow;
170     int y = tileNumber.y() * TILE_SIZE_Y * pow;
171
172     return QPoint(x, y);
173 }
174
175 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
176 {
177     if (isAutoCenteringEnabled()) {
178         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
179
180         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
181                                       m_lastManualPosition.y() / zoomFactor);
182
183         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
184                                       sceneCoordinate.y() / zoomFactor);
185
186         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
187             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
188             return true;
189     }
190
191     return false;
192 }
193
194 void MapEngine::getTiles(QPoint sceneCoordinate)
195 {
196     qDebug() << __PRETTY_FUNCTION__;
197
198     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
199     updateViewTilesSceneRect();
200
201     int topLeftX = m_viewTilesGrid.topLeft().x();
202     int topLeftY = m_viewTilesGrid.topLeft().y();
203     int bottomRightX = m_viewTilesGrid.bottomRight().x();
204     int bottomRightY = m_viewTilesGrid.bottomRight().y();
205
206     int tileMaxVal = tileMaxValue(m_zoomLevel);
207
208     for (int x = topLeftX; x <= bottomRightX; ++x) {
209         for (int y = topLeftY; y <= bottomRightY; ++y) {
210
211             int tileX = x;
212             int tileY = y;
213
214             // span in horizontal direction if world limits has been reached
215 //            if (tileX < 0)
216 //                tileX += tileMaxVal + 1;
217 //            else if (tileX > tileMaxVal)
218 //                tileX -= tileMaxVal + 1;
219
220             // map doesn't span in vertical direction
221             if (tileY < 0 || tileY > tileMaxVal) /// @todo replace variable with method
222                 continue;
223
224             if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, tileX, tileY)))
225                 emit fetchImage(m_zoomLevel, normalizeTileNumberX(tileX), tileY);
226         }
227     }
228
229     QRect spanRect = m_mapScene->spanItems(m_scrollDirection, m_zoomLevel);
230     m_friendItemsHandler->spanHiddenFriendLocationItems(m_scrollDirection, spanRect);
231     m_friendItemsHandler->refactorFriendItems(m_zoomLevel);
232 }
233
234 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
235 {
236     qDebug() << __PRETTY_FUNCTION__;
237
238     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
239
240     if (m_autoCenteringEnabled)
241         setViewLocation(position);
242 }
243
244 void MapEngine::init()
245 {
246     qDebug() << __PRETTY_FUNCTION__;
247
248     QPointF startLocation;
249     QSettings settings(DIRECTORY_NAME, FILE_NAME);
250
251     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
252         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
253         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
254
255         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
256         m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
257     } else {
258         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
259         startLocation = settings.value(MAP_LAST_POSITION,
260                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
261     }
262
263     emit zoomLevelChanged(m_zoomLevel);
264     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
265 }
266
267 bool MapEngine::isAutoCenteringEnabled()
268 {
269     return m_autoCenteringEnabled;
270 }
271
272 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
273 {
274     qDebug() << __PRETTY_FUNCTION__;
275
276     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
277     QPoint temp = m_centerTile;
278     m_centerTile = centerTile;
279
280     return (centerTile != temp);
281 }
282
283 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
284 {
285     if (y != 3)
286         return;
287
288     qWarning() << __PRETTY_FUNCTION__ << "x:" << x << "y:" << y;
289
290     // tile might already be in the scene if expired tile was returned from the cache to be
291     // temporarily displayed while downloading the fresh one
292     QString hashKey = tilePath(zoomLevel, x, y);
293     MapTile *oldTile = m_mapScene->tileInScene(hashKey);
294     if (oldTile)
295         m_mapScene->removeTile(oldTile);
296
297     // add normal tile
298     QPoint tileNumber(x, y);
299     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
300
301     // expanding is only done if received tile zoom level is same as current zoom level
302     if (zoomLevel == m_zoomLevel) {
303         // expand to east side?
304         if (m_viewTilesGrid.right() > tileMaxValue(zoomLevel)) {
305             int crossing = m_viewTilesGrid.right() - tileMaxValue(zoomLevel);
306             if (tileNumber.x() < crossing) {
307                 QPoint adjustedTileNumber(tileNumber.x() + tileMaxValue(zoomLevel) + 1, tileNumber.y());
308                 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
309                 qWarning() << __PRETTY_FUNCTION__ << "duplicate tile to east, x:" << x << "->" << adjustedTileNumber.x() << "y:" << adjustedTileNumber.y();
310             }
311         }
312
313         // expand to west side?
314         if (m_viewTilesGrid.left() < 0) {
315             int crossing = -m_viewTilesGrid.left();
316             if (tileNumber.x() > (tileMaxValue(zoomLevel) - crossing)) {
317                 QPoint adjustedTileNumber(tileNumber.x() - tileMaxValue(zoomLevel) - 1, tileNumber.y());
318                 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
319                 qWarning() << __PRETTY_FUNCTION__ << "duplicate tile to west, x:" << x << "->" << adjustedTileNumber.x() << "y:" << adjustedTileNumber.y();
320             }
321         }
322     }
323
324
325 //    int crossing =  m_tilesGridSize.width() - tileMaxValue(zoomLevel) - 1;
326 ////    qWarning() << __PRETTY_FUNCTION__ << "crossing:" << crossing;
327 //    if (crossing > 0) {
328 //        qWarning() << __PRETTY_FUNCTION__ << "grid was bigger than amount of tiles at this tile level";
329
330 //        if (x < crossing) {
331 //            // expand to east side
332 //            QPoint adjustedTileNumber(tileNumber.x() + tileMaxValue(zoomLevel) + 1, tileNumber.y());
333 //            m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
334 //            qWarning() << __PRETTY_FUNCTION__ << "duplicate tile to east, x:" << x << "->" << adjustedTileNumber.x();
335 //        }
336
337 //        if (x > (tileMaxValue(zoomLevel) - crossing)) {
338 //            // expand to west side
339 //            QPoint adjustedTileNumber(tileNumber.x() - tileMaxValue(zoomLevel) - 1, tileNumber.y());
340 //            m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
341 //            qWarning() << __PRETTY_FUNCTION__ << "duplicate tile to west, x:" << x << "->" << adjustedTileNumber.x();
342 //        }
343 //    }
344
345     m_mapScene->spanItems(m_scrollDirection, m_zoomLevel);
346 }
347
348 int MapEngine::normalizeTileNumberX(int tileX)
349 {
350     int tileMaxVal = tileMaxValue(m_zoomLevel);
351
352     while (tileX < 0)
353         tileX += tileMaxVal + 1;
354
355     while (tileX > tileMaxVal)
356         tileX -= tileMaxVal + 1;
357
358     return tileX;
359 }
360
361 void MapEngine::receiveOwnLocation(User *user)
362 {
363     qDebug() << __PRETTY_FUNCTION__;
364
365     if(user) {
366         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
367         if (m_ownLocation->pos().toPoint() != newPosition) {
368             m_ownLocation->setPos(newPosition);
369         }
370
371         if (!m_ownLocation->isVisible())
372             m_ownLocation->show();
373     }
374     else {
375         m_ownLocation->hide();
376     }
377 }
378
379 QGraphicsScene* MapEngine::scene()
380 {
381     qDebug() << __PRETTY_FUNCTION__;
382
383     return m_mapScene;
384 }
385
386 void MapEngine::setAutoCentering(bool enabled)
387 {
388     m_autoCenteringEnabled = enabled;
389 }
390
391 void MapEngine::setGPSEnabled(bool enabled)
392 {
393     m_gpsLocationItem->setEnabled(enabled);
394 }
395
396 void MapEngine::setLocation(QPoint sceneCoordinate)
397 {
398     qDebug() << __PRETTY_FUNCTION__;
399
400     // jump to opposite side of the world if world limit is exceeded
401     if (sceneCoordinate.x() < 0)
402         sceneCoordinate.setX(sceneCoordinate.x() + WORLD_PIXELS_X);
403     else if (sceneCoordinate.x() > WORLD_PIXELS_X - 1)
404         sceneCoordinate.setX(sceneCoordinate.x() - WORLD_PIXELS_X);
405
406     if (sceneCoordinate.x() > m_sceneCoordinate.x())
407         m_scrollDirection = SCROLL_EAST;
408     else
409         m_scrollDirection = SCROLL_WEST;
410
411     if (disableAutoCentering(sceneCoordinate))
412         emit mapScrolledManually();
413
414     m_sceneCoordinate = sceneCoordinate;
415     emit locationChanged(m_sceneCoordinate);
416
417     if (isCenterTileChanged(sceneCoordinate)) {
418         getTiles(sceneCoordinate);
419         m_mapScene->removeOutOfViewTiles();
420     }
421 }
422
423 void MapEngine::setZoomLevel(int newZoomLevel)
424 {
425     qDebug() << __PRETTY_FUNCTION__;
426
427     m_zoomLevel = newZoomLevel;
428     zoomed();
429 }
430
431 void MapEngine::setTilesGridSize(const QSize &viewSize)
432 {
433     qDebug() << __PRETTY_FUNCTION__;
434
435     // there must be scrolling reserve of at least half tile added to tile amount
436     // calculated from view size
437     const qreal SCROLLING_RESERVE = 0.5;
438
439     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
440     const int CENTER_TILE_INACCURACY = 1;
441
442     int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
443                     + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
444     int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
445                      + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
446
447     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
448
449     m_tilesGridSize.setHeight(gridHeight);
450     m_tilesGridSize.setWidth(gridWidth);
451
452     qWarning() << __PRETTY_FUNCTION__ << "tiles grid:" << m_tilesGridSize.width()
453                                       << "*" << m_tilesGridSize.height();
454 }
455
456 void MapEngine::setViewLocation(QPointF latLonCoordinate)
457 {
458     qDebug() << __PRETTY_FUNCTION__;
459
460     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
461
462     m_lastManualPosition = sceneCoordinate;
463
464     setLocation(sceneCoordinate);
465 }
466
467 int MapEngine::tileMaxValue(int zoomLevel)
468 {
469     qDebug() << __PRETTY_FUNCTION__;
470
471     return (1 << 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 void MapEngine::updateViewTilesSceneRect()
486 {
487     qDebug() << __PRETTY_FUNCTION__;
488
489     const QPoint ONE_TILE = QPoint(1, 1);
490     const QPoint ONE_PIXEL = QPoint(1, 1);
491
492     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
493     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
494     // of the last tile.
495     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
496                                                             m_viewTilesGrid.bottomRight()
497                                                              + ONE_TILE) - ONE_PIXEL;
498
499     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
500 }
501
502 void MapEngine::viewResized(const QSize &size)
503 {
504     qDebug() << __PRETTY_FUNCTION__;
505
506     m_viewSize = size;
507     setTilesGridSize(m_viewSize);
508
509     emit locationChanged(m_sceneCoordinate);
510     getTiles(m_sceneCoordinate);
511     m_mapScene->removeOutOfViewTiles();
512     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
513 }
514
515 void MapEngine::viewZoomFinished()
516 {
517     qDebug() << __PRETTY_FUNCTION__;
518
519     if (m_zoomedIn) {
520         m_zoomedIn = false;
521         m_mapScene->removeOutOfViewTiles();
522     }
523
524     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
525         emit maxZoomLevelReached();
526     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
527         emit minZoomLevelReached();
528 }
529
530 void MapEngine::zoomed()
531 {
532     emit zoomLevelChanged(m_zoomLevel);
533     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
534     getTiles(m_sceneCoordinate);
535     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
536 }
537
538 void MapEngine::zoomIn()
539 {
540     qDebug() << __PRETTY_FUNCTION__;
541
542     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
543         m_zoomLevel++;
544         m_zoomedIn = true;
545         zoomed();
546     }
547 }
548
549 void MapEngine::zoomOut()
550 {
551     qDebug() << __PRETTY_FUNCTION__;
552
553     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
554         m_zoomLevel--;
555         zoomed();
556     }
557 }