forked from minorua/Qgis2threejs
/
qgis2threejsdialog.py
484 lines (402 loc) · 16.9 KB
/
qgis2threejsdialog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Qgis2threejsDialog
A QGIS plugin
export terrain data, map canvas image and vector data to web browser
-------------------
begin : 2013-12-21
copyright : (C) 2013 Minoru Akagi
email : akaginch@gmail.com
RectangleMapTool class is from extentSelector.py of GdalTools plugin
copyright : (C) 2010 by Giuseppe Sucameli
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import QgsMessageBar, QgsMapToolEmitPoint, QgsRubberBand
import os
from ui.ui_qgis2threejsdialog import Ui_Qgis2threejsDialog
from qgis2threejsmain import ObjectTreeItem, MapTo3D, OutputContext, exportToThreeJS
import qgis2threejstools as tools
from quadtree import *
from vectorobject import *
import propertypages as ppages
debug_mode = 1
class Qgis2threejsDialog(QDialog):
STYLE_MAX_COUNT = 4
def __init__(self, iface, properties=None):
QDialog.__init__(self, iface.mainWindow())
self.iface = iface
self.currentItem = None
self.currentPage = None
topItemCount = len(ObjectTreeItem.topItemNames)
if properties is None:
self.properties = [None] * topItemCount
for i in range(ObjectTreeItem.ITEM_OPTDEM, topItemCount):
self.properties[i] = {}
else:
self.properties = properties
# Set up the user interface from Designer.
self.ui = ui = Ui_Qgis2threejsDialog()
ui.setupUi(self)
self.setWindowFlags(self.windowFlags() | Qt.WindowMinimizeButtonHint)
ui.lineEdit_OutputFilename.setPlaceholderText("[Temporary file]")
ui.pushButton_Run.clicked.connect(self.run)
ui.pushButton_Close.clicked.connect(self.reject)
# set up map tool
self.previousMapTool = None
self.mapTool = RectangleMapTool(iface.mapCanvas())
#self.mapTool = PointMapTool(iface.mapCanvas())
# set up the template combo box
self.initTemplateList()
# set up the properties pages
self.pages = {}
self.pages[ppages.PAGE_WORLD] = ppages.WorldPropertyPage(self)
self.pages[ppages.PAGE_CONTROLS] = ppages.ControlsPropertyPage(self)
self.pages[ppages.PAGE_DEM] = ppages.DEMPropertyPage(self)
self.pages[ppages.PAGE_VECTOR] = ppages.VectorPropertyPage(self)
container = ui.propertyPagesContainer
for page in self.pages.itervalues():
page.hide()
container.addWidget(page)
# build object tree
self.topItemPages = {ObjectTreeItem.ITEM_WORLD: ppages.PAGE_WORLD, ObjectTreeItem.ITEM_CONTROLS: ppages.PAGE_CONTROLS, ObjectTreeItem.ITEM_DEM: ppages.PAGE_DEM}
self.initObjectTree()
self.ui.treeWidget.currentItemChanged.connect(self.currentObjectChanged)
self.ui.treeWidget.itemChanged.connect(self.objectItemChanged)
ui.progressBar.setVisible(False)
ui.toolButton_Browse.clicked.connect(self.browseClicked)
#iface.mapCanvas().mapToolSet.connect(self.mapToolSet) # to show button to enable own map tool
self.bar = None # QgsMessageBar
self.localBrowsingMode = True
self.rb_quads = self.rb_point = None
self.objectTypeManager = ObjectTypeManager()
def exec_(self):
ui = self.ui
messages = []
# show message if crs unit is degrees
mapSettings = self.iface.mapCanvas().mapSettings() if QGis.QGIS_VERSION_INT >= 20300 else self.iface.mapCanvas().mapRenderer()
if mapSettings.destinationCrs().mapUnits() in [QGis.Degrees]:
self.showMessageBar("The unit of current CRS is degrees", "Terrain may not appear well.")
self.ui.treeWidget.setCurrentItem(self.ui.treeWidget.topLevelItem(ObjectTreeItem.ITEM_DEM))
return QDialog.exec_(self)
def showMessageBar(self, title, text, level=QgsMessageBar.INFO):
if self.bar is None:
self.bar = QgsMessageBar()
self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
ui = self.ui
margins = ui.gridLayout.getContentsMargins()
vl = ui.gridLayout.takeAt(0)
ui.gridLayout.setContentsMargins(0,0,0,0)
ui.gridLayout.addWidget(self.bar, 0, 0)
ui.gridLayout.addItem(vl, 1, 0)
ui.verticalLayout.setContentsMargins(margins[0], margins[1] / 2, margins[2], margins[3])
self.bar.pushMessage(title, text, level=level)
def initTemplateList(self):
self.ui.comboBox_Template.clear()
templateDir = QDir(tools.templateDir())
for entry in templateDir.entryList(["*.html", "*.htm"]):
self.ui.comboBox_Template.addItem(entry)
# select the last used template
templateName = QSettings().value("/Qgis2threejs/lastTemplate", "", type=unicode)
if templateName:
index = self.ui.comboBox_Template.findText(templateName)
if index != -1:
self.ui.comboBox_Template.setCurrentIndex(index)
return index
return -1
def initObjectTree(self):
tree = self.ui.treeWidget
tree.clear()
# add vector and raster layers into tree widget
topItems = []
for index, itemName in enumerate(ObjectTreeItem.topItemNames):
item = QTreeWidgetItem(tree, [itemName])
item.setData(0, Qt.UserRole, index)
topItems.append(item)
optDEMChecked = False
for layer in self.iface.legendInterface().layers():
layerType = layer.type()
if layerType not in (QgsMapLayer.VectorLayer, QgsMapLayer.RasterLayer):
continue
parentId = None
if layerType == QgsMapLayer.VectorLayer:
geometry_type = layer.geometryType()
if geometry_type in [QGis.Point, QGis.Line, QGis.Polygon]:
parentId = ObjectTreeItem.ITEM_POINT + geometry_type # - QGis.Point
elif layerType == QgsMapLayer.RasterLayer and layer.providerType() == "gdal" and layer.bandCount() == 1:
parentId = ObjectTreeItem.ITEM_OPTDEM
if parentId is None:
continue
item = QTreeWidgetItem(topItems[parentId], [layer.name()])
isVisible = self.properties[parentId].get(layer.id(), {}).get("visible", False) #self.iface.legendInterface().isLayerVisible(layer)
check_state = Qt.Checked if isVisible else Qt.Unchecked
item.setData(0, Qt.CheckStateRole, check_state)
item.setData(0, Qt.UserRole, layer.id())
if parentId == ObjectTreeItem.ITEM_OPTDEM and isVisible:
optDEMChecked = True
for item in topItems:
if item.data(0, Qt.UserRole) != ObjectTreeItem.ITEM_OPTDEM or optDEMChecked:
tree.expandItem(item)
def saveProperties(self, item, page):
properties = page.properties()
parent = item.parent()
if parent is None:
# top item: properties[topItemIndex]
self.properties[item.data(0, Qt.UserRole)] = properties
else:
# layer item: properties[topItemIndex][layerId]
topItemIndex = parent.data(0, Qt.UserRole)
self.properties[topItemIndex][item.data(0, Qt.UserRole)] = properties
if debug_mode:
qDebug(str(self.properties))
def currentObjectChanged(self, currentItem, previousItem):
# save properties of previous item
if previousItem and self.currentPage:
self.saveProperties(previousItem, self.currentPage)
self.currentItem = currentItem
self.currentPage = None
# hide all pages
for page in self.pages.itervalues():
page.hide()
parent = currentItem.parent()
if parent is None:
topItemIndex = currentItem.data(0, Qt.UserRole)
pageType = self.topItemPages.get(topItemIndex, ppages.PAGE_NONE)
page = self.pages.get(pageType, None)
if page is None:
return
page.setup(self.properties[topItemIndex])
page.show()
else:
parentId = parent.data(0, Qt.UserRole)
layerId = currentItem.data(0, Qt.UserRole)
if layerId is None:
return
layer = QgsMapLayerRegistry().instance().mapLayer(layerId)
if layer is None:
return
layerType = layer.type()
if layerType == QgsMapLayer.RasterLayer:
page = self.pages[ppages.PAGE_DEM]
page.setup(self.properties[parentId].get(layerId, None), layer, False)
elif layerType == QgsMapLayer.VectorLayer:
page = self.pages[ppages.PAGE_VECTOR]
page.setup(self.properties[parentId].get(layerId, None), layer)
else:
return
page.show()
self.currentPage = page
def objectItemChanged(self, item, column):
parent = item.parent()
if parent is None:
return
if item == self.currentItem:
if self.currentPage:
# update enablement of property widgets
self.currentPage.itemChanged(item)
else:
# select changed item
self.ui.treeWidget.setCurrentItem(item)
# set visible property
#visible = item.data(0, Qt.CheckStateRole) == Qt.Checked
#parentId = parent.data(0, Qt.UserRole)
#layerId = item.data(0, Qt.UserRole)
#self.properties[parentId].get(layerId, {})["visible"] = visible
def primaryDEMChanged(self, layerId):
tree = self.ui.treeWidget
parent = tree.topLevelItem(ObjectTreeItem.ITEM_OPTDEM)
tree.blockSignals(True)
for i in range(parent.childCount()):
item = parent.child(i)
isPrimary = item.data(0, Qt.UserRole) == layerId
item.setDisabled(isPrimary)
tree.blockSignals(False)
def numericFields(self, layer):
# get attributes of a sample feature and create numeric field name list
numeric_fields = []
f = QgsFeature()
layer.getFeatures().nextFeature(f)
for field in f.fields():
isNumeric = False
try:
float(f.attribute(field.name()))
isNumeric = True
except:
pass
if isNumeric:
numeric_fields.append(field.name())
return numeric_fields
def progress(self, percentage):
self.ui.progressBar.setValue(percentage)
self.ui.progressBar.setVisible(percentage != 100)
def run(self):
ui = self.ui
filename = ui.lineEdit_OutputFilename.text() # ""=Temporary file
if filename != "" and QFileInfo(filename).exists() and QMessageBox.question(None, "Qgis2threejs", "Output file already exists. Overwrite it?", QMessageBox.Ok | QMessageBox.Cancel) != QMessageBox.Ok:
return
self.endPointSelection()
# save properties of current object
item = self.ui.treeWidget.currentItem()
if item and self.currentPage:
self.saveProperties(item, self.currentPage)
ui.pushButton_Run.setEnabled(False)
self.progress(0)
canvas = self.iface.mapCanvas()
templateName = ui.comboBox_Template.currentText()
htmlfilename = ui.lineEdit_OutputFilename.text()
# world properties
world = self.properties[ObjectTreeItem.ITEM_WORLD] or {}
verticalExaggeration = world.get("lineEdit_zFactor", 1.5)
verticalShift = world.get("lineEdit_zShift", 0)
# export to javascript (three.js)
mapTo3d = MapTo3D(canvas, verticalExaggeration=float(verticalExaggeration), verticalShift=float(verticalShift))
context = OutputContext(templateName, mapTo3d, canvas, self.properties, self, self.objectTypeManager, self.localBrowsingMode)
htmlfilename = exportToThreeJS(htmlfilename, context, self.progress)
self.progress(100)
ui.pushButton_Run.setEnabled(True)
if htmlfilename is None:
return
self.clearRubberBands()
# store last selections
settings = QSettings()
settings.setValue("/Qgis2threejs/lastTemplate", templateName)
settings.setValue("/Qgis2threejs/lastControls", context.controls)
# open browser
if not tools.openHTMLFile(htmlfilename):
return
QDialog.accept(self)
def reject(self):
# save properties of current object
item = self.ui.treeWidget.currentItem()
if item and self.currentPage:
self.saveProperties(item, self.currentPage)
self.endPointSelection()
self.clearRubberBands()
QDialog.reject(self)
def startPointSelection(self):
canvas = self.iface.mapCanvas()
if self.previousMapTool != self.mapTool:
self.previousMapTool = canvas.mapTool()
canvas.setMapTool(self.mapTool)
self.pages[ppages.PAGE_DEM].toolButton_PointTool.setVisible(False)
def endPointSelection(self):
self.mapTool.reset()
if self.previousMapTool is not None:
self.iface.mapCanvas().setMapTool(self.previousMapTool)
def mapToolSet(self, mapTool):
return
#TODO: unstable
if mapTool != self.mapTool and self.currentPage is not None:
if self.currentPage.pageType == ppages.PAGE_DEM and self.currentPage.isPrimary:
self.currentPage.toolButton_PointTool.setVisible(True)
def createRubberBands(self, quads, point=None):
self.clearRubberBands()
# create quads with rubber band
self.rb_quads = QgsRubberBand(self.iface.mapCanvas(), QGis.Line)
self.rb_quads.setColor(Qt.blue)
self.rb_quads.setWidth(1)
for quad in quads:
points = []
extent = quad.extent
points.append(QgsPoint(extent.xMinimum(), extent.yMinimum()))
points.append(QgsPoint(extent.xMinimum(), extent.yMaximum()))
points.append(QgsPoint(extent.xMaximum(), extent.yMaximum()))
points.append(QgsPoint(extent.xMaximum(), extent.yMinimum()))
self.rb_quads.addGeometry(QgsGeometry.fromPolygon([points]), None)
self.log(extent.toString())
self.log("Quad count: %d" % len(quads))
# create a point with rubber band
if point:
self.rb_point = QgsRubberBand(self.iface.mapCanvas(), QGis.Point)
self.rb_point.setColor(Qt.red)
self.rb_point.addPoint(point)
def clearRubberBands(self):
# clear quads and point
if self.rb_quads:
self.iface.mapCanvas().scene().removeItem(self.rb_quads)
self.rb_quads = None
if self.rb_point:
self.iface.mapCanvas().scene().removeItem(self.rb_point)
self.rb_point = None
def browseClicked(self):
directory = os.path.split(self.ui.lineEdit_OutputFilename.text())[0]
if directory == "":
directory = QDir.homePath()
filename = QFileDialog.getSaveFileName(self, self.tr("Output filename"), directory, "HTML file (*.html *.htm)", options=QFileDialog.DontConfirmOverwrite)
if filename != "":
self.ui.lineEdit_OutputFilename.setText(filename)
def log(self, msg):
if debug_mode:
qDebug(msg)
class PointMapTool(QgsMapToolEmitPoint):
def __init__(self, canvas):
self.canvas = canvas
QgsMapToolEmitPoint.__init__(self, self.canvas)
self.point = None
def canvasPressEvent(self, e):
self.point = self.toMapCoordinates(e.pos())
self.emit(SIGNAL("pointSelected()"))
# first changed on 2014-01-03 (last changed on 2014-04-20)
class RectangleMapTool(QgsMapToolEmitPoint):
def __init__(self, canvas):
self.canvas = canvas
QgsMapToolEmitPoint.__init__(self, self.canvas)
self.rubberBand = QgsRubberBand(self.canvas, QGis.Polygon)
self.rubberBand.setColor(QColor(255, 0, 0, 180))
self.rubberBand.setWidth(1)
self.reset()
def reset(self):
self.startPoint = self.endPoint = None
self.isEmittingPoint = False
self.rubberBand.reset(QGis.Polygon)
def canvasPressEvent(self, e):
self.startPoint = self.toMapCoordinates(e.pos())
self.endPoint = self.startPoint
self.isEmittingPoint = True
self.showRect(self.startPoint, self.endPoint)
def canvasReleaseEvent(self, e):
self.isEmittingPoint = False
self.emit(SIGNAL("rectangleCreated()"))
def canvasMoveEvent(self, e):
if not self.isEmittingPoint:
return
self.endPoint = self.toMapCoordinates(e.pos())
self.showRect(self.startPoint, self.endPoint)
def showRect(self, startPoint, endPoint):
self.rubberBand.reset(QGis.Polygon)
if startPoint.x() == endPoint.x() or startPoint.y() == endPoint.y():
return
point1 = QgsPoint(startPoint.x(), startPoint.y())
point2 = QgsPoint(startPoint.x(), endPoint.y())
point3 = QgsPoint(endPoint.x(), endPoint.y())
point4 = QgsPoint(endPoint.x(), startPoint.y())
self.rubberBand.addPoint(point1, False)
self.rubberBand.addPoint(point2, False)
self.rubberBand.addPoint(point3, False)
self.rubberBand.addPoint(point4, True) # true to update canvas
self.rubberBand.show()
def rectangle(self):
if self.startPoint == None or self.endPoint == None:
return None
return QgsRectangle(self.startPoint, self.endPoint)
def setRectangle(self, rect):
if rect == self.rectangle():
return False
if rect == None:
self.reset()
else:
self.startPoint = QgsPoint(rect.xMaximum(), rect.yMaximum())
self.endPoint = QgsPoint(rect.xMinimum(), rect.yMinimum())
self.showRect(self.startPoint, self.endPoint)
return True