Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Flooding the terrain on the GPU

Simulate real-time terrain inundation on the GPU in OpenLayers by decoding Terrarium RGB elevation tiles inside a WebGLTileLayer style rule.

OpenStreetMap of Kraków with the Vistula valley east of the city flooded light blue up to 200 m, the Water level slider at 200 and buttons for four towns below.
A screenshot of the example. Elevation: Terrain Tiles on AWS (Mapzen); Europe terrain data produced using Copernicus data and information funded by the European Union - EU-DEM layers; global GMTED2010 and SRTM terrain data courtesy of the U.S. Geological Survey. Map data © OpenStreetMap contributors.

What this example shows

Over OpenStreetMap of Kraków and the Vistula valley ([opacity]="0.6"), scrubbing the Water level slider floods low-lying terrain in crisp light blue ([139, 212, 255, 1]) smoothly on the GPU—paired with preset jump buttons for four regional towns.

When you need it

Compared with CPU worker RasterSource flooding (sea-level), evaluating elevation thresholds inside a WebGL fragment shader eliminates inter-thread pixel copying and responds instantaneously during continuous slider scrubbing and pinch-zooming.

GPU-driven elevation styling scales effortlessly to full-screen 4K and mobile Retina viewports.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

webgl-sea-level.shared.ts
import type { ExpressionValue } from 'ol/expr/expression.js';
import type { Style } from 'ol/layer/WebGLTile.js';

export interface Place {
  name: string;
  lon: number;
  lat: number;
}

/** The Vistula valley and the neighbouring towns, which the buttons move the map to. */
export const PLACES: Place[] = [
  { name: 'Kraków', lon: 19.9368, lat: 50.0614 },
  { name: 'Tarnów', lon: 20.9877, lat: 50.0121 },
  { name: 'Oświęcim', lon: 19.2238, lat: 50.0343 },
  { name: 'Nowy Sącz', lon: 20.6877, lat: 49.6249 },
];

/**
 * The elevation in metres of a Terrarium tile's pixel, `R * 256 + G + B / 256 - 32768`: the band math reads the
 * bands from 0 to 1, so each is scaled by 255.
 */
export const ELEVATION: ExpressionValue = [
  '+',
  -32768,
  ['*', 255 * 256, ['band', 1]],
  ['*', 255, ['band', 2]],
  ['*', 255 / 256, ['band', 3]],
];

/** Light blue where the terrain is at or below the `level` variable, transparent elsewhere. */
export const FLOOD: Style = {
  color: ['case', ['<=', ELEVATION, ['var', 'level']], [139, 212, 255, 1], [139, 212, 255, 0]],
};
webgl-sea-level.ts
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import { fromLonLat } from 'ol/proj';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceImageTileComponent,
  SourceOsmComponent,
  ViewComponent,
} from 'cc-openlayers';
import { LayerWebGLTileComponent } from 'cc-openlayers/webgl';
import { FLOOD, PLACES, type Place } from './webgl-sea-level.shared';

/**
 * The Vistula valley flooded up to a chosen level by a WebGL tile layer: its style compares the elevation of
 * Terrarium tiles with a style variable, which the slider updates in place.
 */
@Component({
  selector: 'app-webgl-sea-level',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerWebGLTileComponent,
    MapComponent,
    SourceImageTileComponent,
    SourceOsmComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="11">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-webgltile [opacity]="0.6" [style]="style" [variables]="variables()">
        <aol-source-imagetile
          url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
          [maxZoom]="15"
          attributions='Elevation: <a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Terrain Tiles</a>'
        />
      </aol-layer-webgltile>
    </aol-map>
    <div class="example-controls">
      <label>
        Water level
        <input type="range" name="level" min="180" max="260" [value]="level()" (input)="setLevel($event)" />
        <output>{{ level() }}</output>
        m above sea level
      </label>
      @for (place of places; track place.name) {
        <button type="button" (click)="goTo(place)">{{ place.name }}</button>
      }
    </div>
  `,
})
export class WebglSeaLevel {
  readonly level = signal(200);
  protected readonly variables = computed(() => ({ level: this.level() }));
  protected readonly style = FLOOD;
  protected readonly places = PLACES;

  private readonly map = viewChild.required(MapComponent);

  protected setLevel(event: Event): void {
    this.level.set((event.target as HTMLInputElement).valueAsNumber);
  }

  protected goTo(place: Place): void {
    const view = this.map().instance.getView();
    view.setCenter(fromLonLat([place.lon, place.lat]));
    view.setZoom(11);
  }
}

Architecture and OpenLayers mechanics

Style expression ELEVATION decodes Terrarium heights from ['band', 1], ['band', 2] and ['band', 3]—multiplying each normalized 0..1 WebGL band value by 255 first before applying (R * 256 + G + B / 256) - 32768.

Conditional colour expression FLOOD outputs [139, 212, 255, 1] wherever the decoded elevation stays at or below ['var', 'level'] and transparent [139, 212, 255, 0] above it, driven reactively via [variables]="variables()".

How it works

  • FLOOD colours pixels [139, 212, 255, 1] at or below ['var', 'level'] and sets alpha 0 above that threshold.
  • ELEVATION multiplies normalized 0..1 values of ['band', 1], ['band', 2] and ['band', 3] by 255 to apply the Terrarium height formula.
  • [variables]="variables()" updates level as a GPU uniform without shader recompilation, rendered at [opacity]="0.6" over OpenStreetMap.

Pitfalls

  • WebGL tile shaders expose standard 8-bit PNG bands normalized from 0 to 1, whereas the Terrarium formula expects 0 to 255 byte values—forgetting * 255 collapses decoded elevations right down near -32768 metres!

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.