fixed review issues
[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 "frienditemshandler.h"
35 #include "mapcommon.h"
36 #include "mapengine.h"
37 #include "maptile.h"
38
39 MapEngine::MapEngine(QObject *parent)
40     : QObject(parent)
41     , m_autoCenteringEnabled(false)
42     , m_centerTile(QPoint(UNDEFINED, UNDEFINED))
43     , m_lastManualPosition(QPoint(0, 0))
44     , m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
45     , m_zoomedIn(false)
46     , m_zoomLevel(DEFAULT_ZOOM_LEVEL)
47 {
48     qDebug() << __PRETTY_FUNCTION__;
49
50     m_mapScene = new MapScene(this);
51
52     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
53     connect(this, SIGNAL(fetchImage(int, int, int)),
54             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
55     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
56             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
57
58     m_ownLocation = new OwnLocationItem();
59     m_ownLocation->hide(); // hide until first location info is received
60     m_mapScene->addItem(m_ownLocation);
61
62     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
63     connect(this, SIGNAL(zoomLevelChanged(int)),
64             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
65     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
66             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
67 }
68
69 void MapEngine::init()
70 {
71     qDebug() << __PRETTY_FUNCTION__;
72
73     emit zoomLevelChanged(m_zoomLevel);
74     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
75 }
76
77 void MapEngine::setViewLocation(QPointF latLonCoordinate)
78 {
79     qDebug() << __PRETTY_FUNCTION__;
80
81     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
82
83     m_lastManualPosition = sceneCoordinate;
84
85     setLocation(sceneCoordinate);
86 }
87
88 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
89 {
90     qDebug() << __PRETTY_FUNCTION__;
91
92     QString hashKey = tilePath(zoomLevel, x, y);
93     if (!m_mapScene->isTileInScene(hashKey)) {
94
95         MapTile *mapTile = new MapTile();
96         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
97         mapTile->setTileNumber(QPoint(x, y));
98         mapTile->setPixmap(image);
99
100         m_mapScene->addTile(mapTile, hashKey);
101
102         m_mapScene->enqueueRemoveStackedTiles(mapTile);
103    }
104 }
105
106 QGraphicsScene* MapEngine::scene()
107 {
108     qDebug() << __PRETTY_FUNCTION__;
109
110     return m_mapScene;
111 }
112
113 int MapEngine::tileMaxValue(int zoomLevel)
114 {
115     qDebug() << __PRETTY_FUNCTION__;
116
117     return (1 << zoomLevel) - 1;
118 }
119
120 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
121 {
122     qDebug() << __PRETTY_FUNCTION__;
123
124     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
125     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
126     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
127     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
128     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
129
130     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
131
132     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
133 }
134
135 void MapEngine::alignImmovableItems(QPoint viewTopLeft)
136 {
137     qDebug() << __PRETTY_FUNCTION__ << "viewTopLeft:" << viewTopLeft;
138 }
139
140 void MapEngine::setLocation(QPoint sceneCoordinate)
141 {
142     qDebug() << __PRETTY_FUNCTION__;
143
144     if (disableAutoCentering(sceneCoordinate))
145         emit mapScrolled();
146
147     m_sceneCoordinate = sceneCoordinate;
148     emit locationChanged(m_sceneCoordinate);
149
150     if (isCenterTileChanged(sceneCoordinate)) {
151         getTiles(sceneCoordinate);
152         m_mapScene->removeOutOfViewTiles();
153     }
154 }
155
156 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
157 {
158     qDebug() << __PRETTY_FUNCTION__;
159
160     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
161     QPoint temp = m_centerTile;
162     m_centerTile = centerTile;
163
164     return (centerTile != temp);
165 }
166
167 void MapEngine::getTiles(QPoint sceneCoordinate)
168 {
169     qDebug() << __PRETTY_FUNCTION__;
170
171     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
172     updateViewTilesSceneRect();
173
174     int topLeftX = m_viewTilesGrid.topLeft().x();
175     int topLeftY = m_viewTilesGrid.topLeft().y();
176     int bottomRightX = m_viewTilesGrid.bottomRight().x();
177     int bottomRightY = m_viewTilesGrid.bottomRight().y();
178
179     int tileMaxVal = tileMaxValue(m_zoomLevel);
180
181     for (int x = topLeftX; x <= bottomRightX; ++x) {
182         for (int y = topLeftY; y <= bottomRightY; ++y) {
183
184             int tileX = x;
185             int tileY = y;
186
187             if (tileX < 0)
188                 tileX += tileMaxVal;
189             else if (tileX > tileMaxVal)
190                 tileX -= tileMaxVal;
191
192             if (tileY < 0)
193                 tileY += tileMaxVal;
194             else if (tileY > tileMaxVal)
195                 tileY -= tileMaxVal;
196
197             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
198                 emit fetchImage(m_zoomLevel, tileX, tileY);
199         }
200     }
201 }
202
203 void MapEngine::updateViewTilesSceneRect()
204 {
205     qDebug() << __PRETTY_FUNCTION__;
206
207     const QPoint ONE_TILE = QPoint(1, 1);
208     const QPoint ONE_PIXEL = QPoint(1, 1);
209
210     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
211     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
212     // of the last tile.
213     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
214                                                             m_viewTilesGrid.bottomRight()
215                                                              + ONE_TILE) - ONE_PIXEL;
216
217     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
218 }
219
220 void MapEngine::viewResized(const QSize &size)
221 {
222     qDebug() << __PRETTY_FUNCTION__;
223
224     m_viewSize = size;
225     getTiles(m_sceneCoordinate);
226     m_mapScene->removeOutOfViewTiles();
227 }
228
229 void MapEngine::viewZoomFinished()
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232
233     if (m_zoomedIn) {
234         m_zoomedIn = false;
235         m_mapScene->removeOutOfViewTiles();
236     }
237 }
238
239 void MapEngine::zoomIn()
240 {
241     qDebug() << __PRETTY_FUNCTION__;
242
243     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
244         m_zoomLevel++;
245         m_zoomedIn = true;
246         emit zoomLevelChanged(m_zoomLevel);
247
248         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
249
250         getTiles(m_sceneCoordinate);
251     }
252 }
253
254 void MapEngine::zoomOut()
255 {
256     qDebug() << __PRETTY_FUNCTION__;
257
258     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
259         m_zoomLevel--;
260         emit zoomLevelChanged(m_zoomLevel);
261
262         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
263
264         getTiles(m_sceneCoordinate);
265     }
266 }
267
268 QString MapEngine::tilePath(int zoomLevel, int x, int y)
269 {
270     qDebug() << __PRETTY_FUNCTION__;
271
272     QString tilePathString(QString::number(zoomLevel) + "/");
273     tilePathString.append(QString::number(x) + "/");
274     tilePathString.append(QString::number(y));
275
276     return tilePathString;
277 }
278
279 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
280 {
281     qDebug() << __PRETTY_FUNCTION__;
282
283     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
284     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
285     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
286
287     return QPoint(x, y);
288 }
289
290 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
291 {
292     qDebug() << __PRETTY_FUNCTION__;
293
294     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
295     int x = tileNumber.x() * TILE_SIZE_X * pow;
296     int y = tileNumber.y() * TILE_SIZE_Y * pow;
297
298     return QPoint(x, y);
299 }
300
301 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
302 {
303     qDebug() << __PRETTY_FUNCTION__;
304
305     qreal longitude = latLonCoordinate.x();
306     qreal latitude = latLonCoordinate.y();
307
308     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
309         return QPoint(UNDEFINED, UNDEFINED);
310     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
311         return QPoint(UNDEFINED, UNDEFINED);
312
313     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
314
315     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
316     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
317                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
318
319     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
320 }
321
322 void MapEngine::receiveOwnLocation(User *user)
323 {
324     qDebug() << __PRETTY_FUNCTION__;
325
326     QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
327     if (m_ownLocation->pos().toPoint() != newPosition) {
328         m_ownLocation->setPos(newPosition);
329     }
330
331     if (!m_ownLocation->isVisible())
332         m_ownLocation->show();
333 }
334
335 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
336 {
337     if (isAutoCenteringEnabled()) {
338         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
339
340         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
341                                       m_lastManualPosition.y() / zoomFactor);
342
343         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
344                                       sceneCoordinate.y() / zoomFactor);
345
346         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
347             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
348             return true;
349     }
350
351     return false;
352 }
353
354 bool MapEngine::isAutoCenteringEnabled()
355 {
356     return m_autoCenteringEnabled;
357 }
358
359 void MapEngine::setAutoCentering(bool enabled)
360 {
361     m_autoCenteringEnabled = enabled;
362 }
363
364 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
365 {   
366     qDebug() << __PRETTY_FUNCTION__;
367
368     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
369     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
370     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
371
372     tileFactor = 1 << zoomLevel;
373     double longitude = xFactor / tileFactor * 360.0 - 180;
374
375     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
376     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
377
378     return QPointF(longitude, latitude);
379 }
380
381 void MapEngine::ownLocation()
382 {
383      qDebug() << __PRETTY_FUNCTION__;    
384
385     emit requestToGetViewPortContents();
386     QPointF ownLatitudeLongitudeLocation =
387             convertSceneCoordinateToLatLon(m_zoomLevel, m_viewArea.center());    
388     emit ownLocation(ownLatitudeLongitudeLocation);
389 }
390
391 void MapEngine::receiveViewSceneRect(QRect viewSceneRect)
392 {
393     qDebug() << __PRETTY_FUNCTION__;
394
395     m_viewArea = viewSceneRect;
396 }