Source code: QGIS 3D map view: turn a DEM into 3D terrain
Runnable Python scripts, requirements and console output for the tutorial “QGIS 3D map view: turn a DEM into 3D terrain”.
Last updated
These are the exact scripts used to produce every figure and number in QGIS 3D map view: turn a DEM into 3D terrain. Download them, install the requirements into a fresh virtual environment and run them from this folder.
- capture_scene.py
- qgis_3d_dem.py
- console.txt: the console output recorded when we ran it
python -m venv .venv.venv\Scripts\activate # macOS/Linux: source .venv/bin/activatepip install -r requirements.txtpython capture_scene.pycapture_scene.py
"""QGIS screenshots for the 3D map view tutorial (run by tools/qgis-capture/scene_shot.ps1).
Opens keswick-3d.qgz (made by qgis_3d_dem.py), then grabs:1. the main window with the tinted DEM and hillshade over Keswick;2. Project > Properties > Terrain with the DEM chosen as the terrain;3. the View menu with New 3D Map View highlighted;4. the 3D map view's configuration dialogue (Terrain page, vertical scale)."""from qgis.core import QgsProject, QgsRectanglefrom qgis.PyQt.QtCore import QTimerfrom qgis.PyQt.QtWidgets import (QAction, QApplication, QDialog, QDockWidget, QListWidget, QMenu, QToolButton, QWidget)
def steps(iface, shot, log): st = {}
def setup(): mw = iface.mainWindow() mw.showNormal() mw.resize(1500, 900) mw.move(40, 40) for dock in mw.findChildren(QDockWidget): if dock.objectName() not in ("Layers",): dock.hide() log(f"layers: {[l.name() for l in QgsProject.instance().mapLayers().values()]}") iface.mapCanvas().setExtent(QgsRectangle(315000, 508500, 347000, 535500)) iface.mapCanvas().refresh()
def grab_main(): shot(iface.mainWindow(), "01-qgis-keswick-dem-2d.png")
def open_props(): QTimer.singleShot(1500, pick_terrain) iface.showProjectPropertiesDialog("") # modal; later steps run inside its event loop
def pick_terrain(): dlg = QApplication.activeModalWidget() st["props"] = dlg lst = dlg.findChild(QListWidget, "mOptionsListWidget") names = [lst.item(i).text() for i in range(lst.count())] log(f"property pages: {names}") for i, n in enumerate(names): if n.lower() in ("terrain", "elevation"): lst.setCurrentRow(i) dlg.resize(1000, 640) QTimer.singleShot(1500, grab_props)
def grab_props(): shot(st["props"], "02-qgis-project-properties-terrain.png") st["props"].reject()
def show_view_menu(): mw = iface.mainWindow() menu = next(m for m in mw.menuBar().findChildren(QMenu) if m.title().replace("&", "") == "View") st["menu"] = menu sub = next((a for a in menu.actions() if "3D Map Views" in a.text().replace("&", "")), None) log(f"view menu: {[a.text() for a in menu.actions()][:12]}") menu.popup(mw.mapToGlobal(mw.menuBar().actionGeometry(menu.menuAction()).bottomLeft())) if sub: menu.setActiveAction(sub) sub.menu().popup(menu.mapToGlobal(menu.actionGeometry(sub).topRight())) st["sub"] = sub.menu() new = next((a for a in sub.menu().actions() if "New 3D Map View" in a.text().replace("&", "")), None) if new: sub.menu().setActiveAction(new) st["new"] = new
def grab_menu(): menu, sub = st["menu"], st.get("sub") # Combine the View menu and its submenu into one picture, placed as they appear on screen. from qgis.PyQt.QtGui import QPainter, QPixmap, QColor a, ra = menu.grab(), menu.geometry() if sub: b, rb = sub.grab(), sub.geometry() left, top = min(ra.left(), rb.left()), min(ra.top(), rb.top()) w = max(ra.right(), rb.right()) - left + 1 h = max(ra.bottom(), rb.bottom()) - top + 1 pix = QPixmap(w, h) pix.fill(QColor("white")) p = QPainter(pix) p.drawPixmap(ra.left() - left, ra.top() - top, a) p.drawPixmap(rb.left() - left, rb.top() - top, b) p.end() pix.save(shot.__globals__["OUTDIR"] + "/03-qgis-view-menu-new-3d-map-view.png") log(f"shot 03-qgis-view-menu-new-3d-map-view.png {w}x{h}") sub.hide() menu.hide()
def open_3d(): new = st.get("new") if new: new.trigger() log("triggered new 3D map view")
def open_config(): mw = iface.mainWindow() docks = [d for d in mw.findChildren(QDockWidget) if d.metaObject().className() == "Qgs3DMapCanvasWidget" or d.findChild(QWidget, "", ) and "3D" in d.windowTitle()] log(f"3D docks: {[(d.windowTitle(), d.metaObject().className()) for d in docks]}") widget = next((w for w in mw.findChildren(QWidget) if w.metaObject().className() == "Qgs3DMapCanvasWidget"), None) if widget is None: for w in QApplication.topLevelWidgets(): widget = widget or next((c for c in w.findChildren(QWidget) if c.metaObject().className() == "Qgs3DMapCanvasWidget"), None) log(f"3D widget: {widget is not None}") acts = [] if widget: for b in widget.findChildren(QToolButton): acts.append((b.toolTip(), b.text())) for a in widget.findChildren(QAction): acts.append((a.toolTip(), a.text())) log(f"3D actions: {acts}") target = None for a in (widget.findChildren(QAction) if widget else []): if "Configure" in a.text() or "Configure" in a.toolTip(): target = a if target: target.trigger() QTimer.singleShot(2500, grab_config) else: log("no configure action")
def grab_config(): dlg = None for t in QApplication.topLevelWidgets(): for c in [t, *t.findChildren(QWidget)]: if c.metaObject().className() == "Qgs3DMapConfigWidget" and c.isVisible(): log(f"config widget in {c.window().metaObject().className()} '{c.window().windowTitle()}' " f"{c.window().width()}x{c.window().height()}") dlg = c.window() log(f"config dialog: {dlg.metaObject().className() if dlg else None}") if not dlg: return lst = dlg.findChild(QListWidget) if lst: log(f"config pages: {[lst.item(i).text() for i in range(lst.count())]}") for i in range(lst.count()): if lst.item(i).text().lower() == "terrain": lst.setCurrentRow(i) dlg.resize(820, 470) from qgis.PyQt.QtWidgets import QAbstractSpinBox, QGroupBox spins = {w.objectName(): w for w in dlg.findChildren(QAbstractSpinBox)} log(f"config spins: {sorted(spins)}") for name, value in (("spinTerrainScale", 1.5), ("spinTerrainResolution", 64), ("spinTerrainSkirtHeight", 60)): if name in spins: spins[name].setValue(value) for g in dlg.findChildren(QGroupBox): if g.title().replace("&", "") == "Terrain Shading": g.setChecked(True) QApplication.processEvents() QTimer.singleShot(1200, lambda: (shot(dlg, "04-qgis-3d-configure-terrain.png"), dlg.reject()))
return [ (500, setup), (8000, grab_main), (500, open_props), (3000, show_view_menu), (1500, grab_menu), (500, open_3d), (6000, open_config), (6000, lambda: log("config done")), (6000, lambda: log("end")), ]qgis_3d_dem.py
"""QGIS 3D map view from a DEM: Keswick, Derwentwater and Skiddaw from Copernicus GLO-30.
Run with the Python that ships with QGIS (no pip packages needed): "C:\\Program Files\\QGIS 3.40.12\\bin\\python-qgis-ltr.bat" qgis_3d_dem.py
What it does 1. Cuts a 26 x 24 km window out of the Copernicus GLO-30 tiles N54 W004 and N54 W003 (the window straddles 3 degrees west) straight from the AWS Open Data bucket (no download of the whole tiles) and reprojects it to British National Grid (EPSG:27700) at 25 m, because the QGIS 3D view needs a projected CRS in metres. 2. Makes a hillshade and a colour-ramped DEM to drape over the terrain. 3. Builds a QGIS project with the DEM set as the project terrain (Project > Properties > Terrain), which is what every new 3D map view uses. 4. Renders three 3D views with the QGIS 3D engine through a print layout 3D Map item and saves the project, so you can open it and press View > 3D Map Views > New 3D Map View.
Copernicus DEM GLO-30: (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018,provided under COPERNICUS by the European Union and ESA; all rights reserved. Free to use withthis credit."""import mathimport osimport sysimport time
from osgeo import gdalfrom qgis.core import ( QgsApplication, QgsColorRampShader, QgsCoordinateReferenceSystem, QgsHillshadeRenderer, QgsLayout, QgsLayoutExporter, QgsLayoutItemPage, QgsLayoutPoint, QgsLayoutSize, QgsPrintLayout, QgsProject, QgsRasterBandStats, QgsRasterDemTerrainProvider, QgsRasterLayer, QgsRasterShader, QgsRectangle, QgsSingleBandPseudoColorRenderer, QgsStyle, QgsUnitTypes, QgsVector3D, QgsPainting,)from qgis.PyQt.QtCore import QSizefrom qgis.PyQt.QtGui import QColor, QImage, QPainterfrom qgis.PyQt.QtXml import QDomDocumentfrom qgis.core import QgsReadWriteContext
HERE = os.path.dirname(os.path.abspath(__file__))OUT = os.path.join(HERE, "output")os.makedirs(OUT, exist_ok=True)
TILES = [f"/vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_N54_00_{t}_00_DEM/" f"Copernicus_DSM_COG_10_N54_00_{t}_00_DEM.tif" for t in ("W004", "W003")]# British National Grid window: Bassenthwaite and Skiddaw in the north, Borrowdale in the south,# Thirlmere and Helvellyn's ridge in the east.BNG = (318000, 510000, 344000, 534000) # xmin, ymin, xmax, ymaxDEM = os.path.join(OUT, "keswick_dem_bng_25m.tif")HILL = os.path.join(OUT, "keswick_hillshade.tif")PROJECT = os.path.join(OUT, "keswick-3d.qgz")
def cut_dem(): t0 = time.time() gdal.UseExceptions() gdal.SetConfigOption("GDAL_DISABLE_READDIR_ON_OPEN", "EMPTY_DIR") gdal.Warp(DEM, TILES, dstSRS="EPSG:27700", outputBounds=BNG, xRes=25, yRes=25, resampleAlg="cubic", outputType=gdal.GDT_Float32, dstNodata=-9999, creationOptions=["COMPRESS=DEFLATE", "PREDICTOR=3", "TILED=YES"]) gdal.DEMProcessing(HILL, DEM, "hillshade", zFactor=1.0, azimuth=315, altitude=40, combined=False, creationOptions=["COMPRESS=DEFLATE"]) ds = gdal.Open(DEM) b = ds.GetRasterBand(1) mn, mx, mean, sd = b.ComputeStatistics(False) print(f"DEM: {ds.RasterXSize} x {ds.RasterYSize} cells at 25 m, EPSG:27700, " f"{mn:.0f} m to {mx:.0f} m (mean {mean:.0f} m) in {time.time() - t0:.1f} s") return mn, mx
def build_project(mn, mx): project = QgsProject.instance() project.clear() project.setCrs(QgsCoordinateReferenceSystem("EPSG:27700")) project.setFileName(PROJECT)
dem = QgsRasterLayer(DEM, "Copernicus GLO-30 DEM (25 m)") hill = QgsRasterLayer(HILL, "Hillshade") assert dem.isValid() and hill.isValid()
# A hypsometric tint: valley floors green, fell sides tan and brown, summits pale grey. stops = [(60, "#5b8c51"), (150, "#8db36a"), (300, "#d6cf8f"), (500, "#c49a6c"), (700, "#9b7b62"), (950, "#eeeae4")] shader_fn = QgsColorRampShader(mn, mx) shader_fn.setColorRampType(QgsColorRampShader.Interpolated) shader_fn.setColorRampItemList([QgsColorRampShader.ColorRampItem(v, QColor(c), f"{v} m") for v, c in stops]) shader = QgsRasterShader() shader.setRasterShaderFunction(shader_fn) renderer = QgsSingleBandPseudoColorRenderer(dem.dataProvider(), 1, shader) renderer.setClassificationMin(stops[0][0]) renderer.setClassificationMax(stops[-1][0]) dem.setRenderer(renderer)
hill.setBlendMode(QPainter.CompositionMode_Multiply) hill.renderer().setOpacity(0.55)
project.addMapLayer(dem) project.addMapLayer(hill) # Order in the Layers panel: hillshade on top, multiplied over the colour ramp. root = project.layerTreeRoot() node = root.findLayer(hill.id()) clone = node.clone() root.insertChildNode(0, clone) node.parent().removeChildNode(node)
# Project > Properties > Terrain: use the DEM as the terrain every 3D view drapes onto. terrain = QgsRasterDemTerrainProvider() terrain.setLayer(dem) terrain.setScale(1.0) project.elevationProperties().setTerrainProvider(terrain) return project, dem, hill
def render_views(project, dem, hill): from qgis._3d import Qgs3DMapSettings, QgsCameraPose, QgsLayoutItem3DMap, QgsDirectionalLightSettings
ext = QgsRectangle(*BNG) s = Qgs3DMapSettings() s.setTransformContext(project.transformContext()) s.setPathResolver(project.pathResolver()) # Qgs3DMapSettings has no Python setter for the terrain generator in QGIS 3.40, so we give it # the same <terrain> element the 3D view writes into a project: a DEM generator on our layer. doc = QDomDocument() root = doc.createElement("qgis3d") doc.appendChild(root) e = doc.createElement("extent") for k, v in zip(("xMin", "yMin", "xMax", "yMax"), BNG): e.setAttribute(k, str(v)) root.appendChild(e) o = doc.createElement("origin") o.setAttribute("x", str(ext.center().x())); o.setAttribute("y", str(ext.center().y())); o.setAttribute("z", "0") root.appendChild(o) c = doc.createElement("crs") project.crs().writeXml(c, doc) root.appendChild(c) t = doc.createElement("terrain") t.setAttribute("exaggeration", "1.5") t.setAttribute("texture-size", "1024") t.setAttribute("max-terrain-error", "1.5") t.setAttribute("max-ground-error", "1") g = doc.createElement("generator") g.setAttribute("type", "dem") g.setAttribute("layer", dem.id()) g.setAttribute("resolution", "64") g.setAttribute("skirt-height", "60") t.appendChild(g) root.appendChild(t) ctx = QgsReadWriteContext() ctx.setPathResolver(project.pathResolver()) ctx.setTransformContext(project.transformContext()) s.readXml(root, ctx) s.resolveReferences(project) s.setLayers([hill, dem]) s.setBackgroundColor(QColor("#dfe9f3")) s.setFieldOfView(40) light = QgsDirectionalLightSettings() light.setDirection(QgsVector3D(0.6, -0.8, -0.4)) light.setIntensity(0.9) s.setLightSources([light]) s.setTerrainShadingEnabled(True)
views = { # name: (look-at x, y in BNG, distance m, pitch deg, heading deg) # Heading turns anticlockwise: 0 puts the camera south looking north, 90 east looking west. "lake-district-from-south-west": (331000, 522500, 23000, 56, 315), "derwentwater-borrowdale-from-north": (326000, 517500, 15000, 60, 180), "skiddaw-blencathra-from-south": (330000, 528000, 14000, 62, 0), } if os.environ.get("VIEWS") == "test": views = {"_test-top": (331000, 522000, 30000, 0, 0), "_test-h0": (331000, 522000, 30000, 60, 0), "_test-h90": (331000, 522000, 30000, 60, 90)} results = [] for name, (x, y, dist, pitch, heading) in views.items(): layout = QgsPrintLayout(project) layout.initializeDefaults() page = layout.pageCollection().page(0) page.setPageSize(QgsLayoutSize(320, 180, QgsUnitTypes.LayoutMillimeters)) item = QgsLayoutItem3DMap(layout) layout.addLayoutItem(item) item.attemptMove(QgsLayoutPoint(0, 0)) item.attemptResize(QgsLayoutSize(320, 180, QgsUnitTypes.LayoutMillimeters)) item.setBackgroundColor(QColor("#dfe9f3")) item.setMapSettings(Qgs3DMapSettings(s)) pose = QgsCameraPose() # QGIS 3.40 3D world coordinates: x = east, y = up, z = south (relative to the origin). pose.setCenterPoint(QgsVector3D(x - s.origin().x(), 300, -(y - s.origin().y()))) pose.setDistanceFromCenterPoint(dist) pose.setPitchAngle(pitch) pose.setHeadingAngle(heading) item.setCameraPose(pose) png = os.path.join(OUT, f"{name}.png") settings = QgsLayoutExporter.ImageExportSettings() settings.dpi = 150 t0 = time.time() # The 3D item renders on its own offscreen engine and loads terrain tiles in the # background, so export every two seconds until two exports in a row are identical. previous, stable = None, 0 while time.time() - t0 < 180: res = QgsLayoutExporter(layout).exportToImage(png, settings) with open(png, "rb") as f: current = f.read() stable = stable + 1 if previous == current else 0 if stable >= 3 and time.time() - t0 > 20: break previous = current end = time.time() + 2 while time.time() < end: QgsApplication.processEvents() time.sleep(0.02) img = QImage(png) print(f"{name}: export result {res}, {img.width()} x {img.height()} px, stable after {time.time() - t0:.0f} s") results.append((name, png)) return results
def main(): mn, mx = cut_dem() project, dem, hill = build_project(mn, mx) render_views(project, dem, hill) project.write() print(f"Project saved: {os.path.relpath(PROJECT, HERE)}")
if __name__ == "__main__": qgs = QgsApplication([], True) qgs.initQgis() try: main() finally: qgs.exitQgis()