"""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 with this credit. """ import math import os import sys import time from osgeo import gdal from 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 QSize from qgis.PyQt.QtGui import QColor, QImage, QPainter from qgis.PyQt.QtXml import QDomDocument from 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, ymax DEM = 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 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()