4b6836094ef384fa0f37972627ba6603dec20687
[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
9    Situare is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License
11    version 2 as published by the Free Software Foundation.
12
13    Situare is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Situare; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
21    USA.
22 */
23
24 #include <QtAlgorithms>
25 #include <QDebug>
26 #include <QString>
27 #include <QStringList>
28 #include <QUrl>
29 #include <QHash>
30 #include <QHashIterator>
31 #include <QRect>
32
33 #include "mapengine.h"
34 #include "maptile.h"
35
36 MapEngine::MapEngine(QObject *parent)
37     : QObject(parent)
38     , m_centerTile(QPoint(UNDEFINED, UNDEFINED))
39     , m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
40     , m_zoomedIn(false)
41     , m_zoomLevel(DEFAULT_ZOOM_LEVEL)
42 {
43     qDebug() << __PRETTY_FUNCTION__;
44
45     m_mapScene = new MapScene(this);
46
47     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
48     connect(this, SIGNAL(fetchImage(int,int,int)),
49             m_mapFetcher, SLOT(enqueueFetchMapImage(int,int,int)));
50     connect(m_mapFetcher, SIGNAL(mapImageReceived(int,int,int,QPixmap)),
51             this, SLOT(mapImageReceived(int,int,int,QPixmap)));
52
53     m_mapZoomPanel = new MapZoomPanel(NULL, MAP_ZOOM_PANEL_POSITION_X, MAP_ZOOM_PANEL_POSITION_Y);
54     m_mapScene->addItem(m_mapZoomPanel);
55     connect(m_mapZoomPanel, SIGNAL(zoomInPressed()), this, SLOT(zoomIn()));
56     connect(m_mapZoomPanel, SIGNAL(zoomOutPressed()), this, SLOT(zoomOut()));
57
58    m_ownLocation = new OwnLocationItem(QPointF());
59 }
60
61 MapEngine::~MapEngine()
62 {
63     qDeleteAll(m_friendsLocations.begin(),m_friendsLocations.end());
64     m_friendsLocations.clear();
65 }
66
67 void MapEngine::init()
68 {
69     qDebug() << __PRETTY_FUNCTION__;
70
71     emit zoomLevelChanged(m_zoomLevel);
72     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
73 }
74
75 void MapEngine::setViewLocation(QPointF latLonCoordinate)
76 {
77     qDebug() << __PRETTY_FUNCTION__;
78
79     setLocation(convertLatLonToSceneCoordinate(latLonCoordinate));
80 }
81
82 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
83 {
84     qDebug() << __PRETTY_FUNCTION__;
85
86     QString hashKey = tilePath(zoomLevel, x, y);
87     if (!m_mapScene->isTileInScene(hashKey)) {
88
89         MapTile *mapTile = new MapTile();
90         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
91         mapTile->setTileNumber(QPoint(x, y));
92         mapTile->setPixmap(image);
93
94         m_mapScene->addTile(mapTile, hashKey);
95
96         m_mapScene->enqueueRemoveStackedTiles(mapTile);
97    }
98 }
99
100 QGraphicsScene* MapEngine::scene()
101 {
102     qDebug() << __PRETTY_FUNCTION__;
103
104     return m_mapScene;
105 }
106
107 int MapEngine::tileMaxValue(int zoomLevel)
108 {
109     qDebug() << __PRETTY_FUNCTION__;
110
111     return (1 << zoomLevel) - 1;
112 }
113
114 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
115 {
116     qDebug() << __PRETTY_FUNCTION__;
117
118     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
119     int gridWidth = (m_viewSize.width()/TILE_SIZE_X + 1) + (GRID_PADDING*2);
120     int gridHeight = (m_viewSize.height()/TILE_SIZE_Y + 1) + (GRID_PADDING*2);
121     int topLeftX = tileCoordinate.x() - (gridWidth/2);
122     int topLeftY = tileCoordinate.y() - (gridHeight/2);
123
124     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
125
126     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
127 }
128
129 void MapEngine::alignImmovableItems(QPoint viewTopLeft)
130 {
131     qDebug() << __PRETTY_FUNCTION__ << "viewTopLeft:" << viewTopLeft;
132
133     m_mapZoomPanel->setPos(viewTopLeft);
134 }
135
136 void MapEngine::setLocation(QPoint sceneCoordinate)
137 {
138     qDebug() << __PRETTY_FUNCTION__;
139
140     m_sceneCoordinate = sceneCoordinate;
141     emit locationChanged(m_sceneCoordinate);
142
143     if (isCenterTileChanged(sceneCoordinate)) {
144         getTiles(sceneCoordinate);
145         m_mapScene->removeOutOfViewTiles();
146     }
147 }
148
149 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
150 {
151     qDebug() << __PRETTY_FUNCTION__;
152
153     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
154     QPoint temp = m_centerTile;
155     m_centerTile = centerTile;
156
157     return (centerTile != temp);
158 }
159
160 void MapEngine::getTiles(QPoint sceneCoordinate)
161 {
162     qDebug() << __PRETTY_FUNCTION__;
163
164     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
165     updateViewTilesSceneRect();
166
167     int topLeftX = m_viewTilesGrid.topLeft().x();
168     int topLeftY = m_viewTilesGrid.topLeft().y();
169     int bottomRightX = m_viewTilesGrid.bottomRight().x();
170     int bottomRightY = m_viewTilesGrid.bottomRight().y();
171
172     int tileMaxVal = tileMaxValue(m_zoomLevel);
173
174     for (int x = topLeftX; x <= bottomRightX; ++x) {
175         for (int y = topLeftY; y <= bottomRightY; ++y) {
176
177             int tileX = x;
178             int tileY = y;
179
180             if (tileX < 0)
181                 tileX += tileMaxVal;
182             else if (tileX > tileMaxVal)
183                 tileX -= tileMaxVal;
184
185             if (tileY < 0)
186                 tileY += tileMaxVal;
187             else if (tileY > tileMaxVal)
188                 tileY -= tileMaxVal;
189
190             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
191                 emit fetchImage(m_zoomLevel, tileX, tileY);
192         }
193     }
194 }
195
196 void MapEngine::updateViewTilesSceneRect()
197 {
198     qDebug() << __PRETTY_FUNCTION__;
199
200     const QPoint ONE_TILE = QPoint(1, 1);
201     const QPoint ONE_PIXEL = QPoint(1, 1);
202
203     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
204     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
205     // of the last tile.
206     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
207                                                             m_viewTilesGrid.bottomRight()
208                                                              + ONE_TILE) - ONE_PIXEL;
209
210     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
211 }
212
213 void MapEngine::viewResized(const QSize &size)
214 {
215     qDebug() << __PRETTY_FUNCTION__;
216
217     m_viewSize = size;
218     getTiles(m_sceneCoordinate);
219     m_mapScene->removeOutOfViewTiles();
220 }
221
222 void MapEngine::viewZoomFinished()
223 {
224     qDebug() << __PRETTY_FUNCTION__;
225
226     if (m_zoomedIn) {
227         m_zoomedIn = false;
228         m_mapScene->removeOutOfViewTiles();
229     }
230 }
231
232 void MapEngine::zoomIn()
233 {
234     qDebug() << __PRETTY_FUNCTION__;
235
236     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
237         m_zoomLevel++;
238         m_zoomedIn = true;
239         emit zoomLevelChanged(m_zoomLevel);
240
241         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
242
243         getTiles(m_sceneCoordinate);
244     }
245 }
246
247 void MapEngine::zoomOut()
248 {
249     qDebug() << __PRETTY_FUNCTION__;
250
251     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
252         m_zoomLevel--;
253         emit zoomLevelChanged(m_zoomLevel);
254
255         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
256
257         getTiles(m_sceneCoordinate);
258     }
259 }
260
261 QString MapEngine::tilePath(int zoomLevel, int x, int y)
262 {
263     qDebug() << __PRETTY_FUNCTION__;
264
265     QString tilePathString(QString::number(zoomLevel) + "/");
266     tilePathString.append(QString::number(x) + "/");
267     tilePathString.append(QString::number(y));
268
269     return tilePathString;
270 }
271
272 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
273 {
274     qDebug() << __PRETTY_FUNCTION__;
275
276     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
277     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X*pow));
278     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y*pow));
279
280     return QPoint(x, y);
281 }
282
283 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
284 {
285     qDebug() << __PRETTY_FUNCTION__;
286
287     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
288     int x = tileNumber.x() * TILE_SIZE_X * pow;
289     int y = tileNumber.y() * TILE_SIZE_Y * pow;
290
291     return QPoint(x, y);
292 }
293
294 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     qreal longitude = latLonCoordinate.x();
299     qreal latitude = latLonCoordinate.y();
300
301     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
302         return QPoint(UNDEFINED, UNDEFINED);
303     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
304         return QPoint(UNDEFINED, UNDEFINED);
305
306     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
307
308     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
309     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
310                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
311
312     return QPointF(x*z*TILE_SIZE_X, y*z*TILE_SIZE_Y).toPoint();
313 }
314
315 void MapEngine::receiveOwnLocation(User *user)
316 {
317     qDebug() << __PRETTY_FUNCTION__;
318     m_ownLocation->setPosition(user->coordinates());
319     m_mapScene->addItem(m_ownLocation);
320 }
321
322 void MapEngine::receiveFriendLocations(QList<User *> &friendsList)
323 {
324     qDebug() << __PRETTY_FUNCTION__;
325     qDeleteAll(m_friendsLocations.begin(),m_friendsLocations.end());
326     m_friendsLocations.clear();
327
328     for(int i=0; i<friendsList.count(); i++) {
329         FriendLocationItem *friendLocation
330                 = new FriendLocationItem(friendsList.at(i)->profileImage(),
331                                          friendsList.at(i)->coordinates(),0);
332
333         friendLocation->setUserId(friendsList.at(i)->userId());
334         m_friendsLocations.append(friendLocation);
335         m_mapScene->addItem(friendLocation);
336     }
337 }