cc3fae094fe06d25088262e6a9bf5579be2d712b
[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 <QDebug>
25 #include <QString>
26 #include <QStringList>
27 #include <QUrl>
28 #include <QHash>
29 #include <QHashIterator>
30 #include <QRect>
31
32 #include "mapengine.h"
33 #include "maptile.h"
34
35 MapEngine::MapEngine(QObject *parent)
36     : QObject(parent)
37     , m_centerTile(QPoint(UNDEFINED, UNDEFINED))
38     , m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
39     , m_zoomLevel(DEFAULT_ZOOM_LEVEL)
40 {
41     m_mapScene = new MapScene(this);
42
43     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
44     connect(this, SIGNAL(fetchImage(QUrl)), m_mapFetcher, SLOT(fetchMapImage(QUrl)));
45     connect(m_mapFetcher, SIGNAL(mapImageReceived(QUrl,QPixmap)), this,
46             SLOT(mapImageReceived(QUrl, QPixmap)));
47
48     m_mapZoomPanel = new MapZoomPanel(NULL, MAP_ZOOM_PANEL_POSITION_X, MAP_ZOOM_PANEL_POSITION_Y);
49     m_mapScene->addItem(m_mapZoomPanel);
50     connect(m_mapZoomPanel, SIGNAL(zoomInPressed()), this, SLOT(zoomIn()));
51     connect(m_mapZoomPanel, SIGNAL(zoomOutPressed()), this, SLOT(zoomOut()));
52
53     m_ownLocation = new OwnLocationItem();
54     m_mapScene->addItem(m_ownLocation);
55 }
56
57 void MapEngine::init()
58 {
59     emit zoomLevelChanged(m_zoomLevel);
60     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
61 }
62
63 void MapEngine::setViewLocation(QPointF latLonCoordinate)
64 {
65     qDebug() << __PRETTY_FUNCTION__;
66     setLocation(convertLatLonToSceneCoordinate(latLonCoordinate));
67 }
68
69 QUrl MapEngine::buildURL(int zoomLevel, QPoint tileNumbers)
70 {
71     QString url = QString("http://tile.openstreetmap.org/mapnik/%1/%2/%3.png")
72                   .arg(zoomLevel).arg(tileNumbers.x()).arg(tileNumbers.y());
73
74     return QUrl(url);
75 }
76
77 void MapEngine::parseURL(const QUrl &url, int &zoom, int &x, int &y)
78 {
79     QString path = url.path();
80     QStringList pathParts = path.split("/", QString::SkipEmptyParts);
81
82     int size = pathParts.size();
83
84     if (size >= 3) {
85         zoom = (pathParts.at(size-3)).toInt();
86         x = (pathParts.at(size-2)).toInt();
87         QString yString = pathParts.at(size-1);
88         yString.chop(4);
89         y = yString.toInt();
90     }
91 }
92
93 void MapEngine::mapImageReceived(const QUrl &url, const QPixmap &pixmap)
94 {
95     //qDebug() << __PRETTY_FUNCTION__;
96
97     int zoom = UNDEFINED;
98     int x = UNDEFINED;
99     int y = UNDEFINED;
100
101     parseURL(url, zoom, x, y);
102     QString hashKey = tilePath(zoom, x, y);
103     if (!m_mapScene->isTileInScene(hashKey)) {
104
105         MapTile *mapTile = new MapTile();
106         mapTile->setZoomLevel(zoom);
107         mapTile->setTileNumber(QPoint(x, y));
108         mapTile->setPixmap(pixmap);
109
110         m_mapScene->addTile(mapTile, hashKey);
111
112         m_mapScene->removeStackedTiles(mapTile, viewRect());
113    }
114 }
115
116 QGraphicsScene* MapEngine::scene()
117 {
118     return dynamic_cast<QGraphicsScene *>(m_mapScene);
119 }
120
121 int MapEngine::tileMaxValue(int zoomLevel)
122 {
123     return (1 << zoomLevel) - 1;
124 }
125
126 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
127 {
128     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
129     int gridWidth = (m_viewSize.width()/TILE_SIZE_X + 1) + (GRID_PADDING*2);
130     int gridHeight = (m_viewSize.height()/TILE_SIZE_Y + 1) + (GRID_PADDING*2);
131     int topLeftX = tileCoordinate.x() - (gridWidth/2);
132     int topLeftY = tileCoordinate.y() - (gridHeight/2);
133
134     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
135 }
136
137 void MapEngine::alignImmovableItems(QPoint viewTopLeft)
138 {
139     m_mapZoomPanel->setPos(viewTopLeft);
140
141 //    qDebug() << __PRETTY_FUNCTION__ << "viewTopLeft:" << viewTopLeft;
142 }
143
144 void MapEngine::setLocation(QPoint sceneCoordinate)
145 {
146 //    qDebug() << __PRETTY_FUNCTION__;
147
148     m_sceneCoordinate = sceneCoordinate;
149     emit locationChanged(m_sceneCoordinate);
150
151     if (isCenterTileChanged(sceneCoordinate)) {
152         getTiles(sceneCoordinate);
153         m_mapScene->removeOutOfViewTiles(viewRect());
154     }
155 }
156
157 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
158 {
159     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
160     QPoint temp = m_centerTile;
161     m_centerTile = centerTile;
162
163     return (centerTile != temp);
164 }
165
166 void MapEngine::getTiles(QPoint sceneCoordinate)
167 {
168 //    qDebug() << __PRETTY_FUNCTION__;
169
170     m_viewGrid = calculateTileGrid(sceneCoordinate);
171
172     int topLeftX = m_viewGrid.topLeft().x();
173     int topLeftY = m_viewGrid.topLeft().y();
174     int bottomRightX = m_viewGrid.bottomRight().x();
175     int bottomRightY = m_viewGrid.bottomRight().y();
176
177     int tileMaxVal = tileMaxValue(m_zoomLevel);
178
179     for (int x = topLeftX; x <= bottomRightX; ++x) {
180         for (int y = topLeftY; y <= bottomRightY; ++y) {
181
182             int tileX = x;
183             int tileY = y;
184
185             if (tileX < 0)
186                 tileX += tileMaxVal;
187             else if (tileX > tileMaxVal)
188                 tileX -= tileMaxVal;
189
190             if (tileY < 0)
191                 tileY += tileMaxVal;
192             else if (tileY > tileMaxVal)
193                 tileY -= tileMaxVal;
194
195             QUrl url = buildURL(m_zoomLevel, QPoint(tileX, tileY));
196
197             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
198                 emit fetchImage(url);
199         }
200     }
201 }
202
203 QRect MapEngine::viewRect()
204 {
205     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewGrid.topLeft());
206     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewGrid.bottomRight()
207                                                              + QPoint(1, 1));
208     return QRect(topLeft, bottomRight);
209 }
210
211 void MapEngine::viewResized(const QSize &size)
212 {
213     m_viewSize = size;
214     getTiles(m_sceneCoordinate);
215     m_mapScene->removeOutOfViewTiles(viewRect());
216 }
217
218 void MapEngine::viewZoomInFinished()
219 {
220     qDebug() << __PRETTY_FUNCTION__;
221     m_mapScene->removeOutOfViewTiles(viewRect());
222 }
223
224 void MapEngine::zoomIn()
225 {
226 //    qDebug() << __PRETTY_FUNCTION__;
227
228     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
229         m_zoomLevel++;
230         emit zoomLevelChanged(m_zoomLevel);
231
232         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
233
234         getTiles(m_sceneCoordinate);
235     }
236 }
237
238 void MapEngine::zoomOut()
239 {
240 //    qDebug() << __PRETTY_FUNCTION__;
241
242     if (m_zoomLevel > MIN_MAP_ZOOM_LEVEL) {
243         m_zoomLevel--;
244         emit zoomLevelChanged(m_zoomLevel);
245
246         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
247
248         getTiles(m_sceneCoordinate);
249     }
250 }
251
252 QString MapEngine::tilePath(int zoomLevel, int x, int y)
253 {
254     QString tilePathString(QString::number(zoomLevel) + "/");
255     tilePathString.append(QString::number(x) + "/");
256     tilePathString.append(QString::number(y));
257
258     return tilePathString;
259 }
260
261 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
262 {
263     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
264     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X*pow));
265     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y*pow));
266
267     return QPoint(x, y);
268 }
269
270 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
271 {
272     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
273     int x = tileNumber.x() * TILE_SIZE_X * pow;
274     int y = tileNumber.y() * TILE_SIZE_Y * pow;
275
276     return QPoint(x, y);
277 }
278
279 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
280 {
281 //    qDebug() << __PRETTY_FUNCTION__;
282
283     qreal longitude = latLonCoordinate.x();
284     qreal latitude = latLonCoordinate.y();
285
286     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
287         return QPoint(UNDEFINED, UNDEFINED);
288     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
289         return QPoint(UNDEFINED, UNDEFINED);
290
291     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
292
293     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
294     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
295                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
296
297     return QPointF(x*z*TILE_SIZE_X, y*z*TILE_SIZE_Y).toPoint();
298 }