@carto/ps-cog
v0.18.0
Published
Framework-agnostic client library for rendering cloud-native rasters in the CARTO ecosystem.
Maintainers
Keywords
Readme
@carto/ps-cog
deck.gl layers and helpers to render Cloud Optimized GeoTIFFs in the browser. Any dtype, any band combination, mosaics from STAC or GeoJSON, and private buckets through your own signer. It has no framework code and runs in any deck.gl host.
Needs a browser with WebGL2. ESM only.
Install
npm i @carto/ps-cog proj4 @cogeotiff/core \
@deck.gl/core @deck.gl/layers @deck.gl/geo-layers @deck.gl/mesh-layers \
@luma.gl/core @luma.gl/shadertools \
@developmentseed/deck.gl-geotiff @developmentseed/deck.gl-raster \
@developmentseed/geotiff @developmentseed/projInstall the exact peer versions this package lists (npm view @carto/ps-cog peerDependencies). Keep one copy of proj4, @deck.gl/* and @luma.gl/* in the app.
The @developmentseed/* peers are one train and move together. Upstream layers on the current train draw an opened COGSource. openCog still resolves a GeoTIFF, COGTileLayer still takes it as geotiff and wraps it for upstream, and MosaicTileLayer still takes sources. The other packages of the train (affine, morecantile, range-reader, raster-reproject) arrive as dependencies of the four above, and a lockfile must hold them on the same version too. npm ls @developmentseed/geotiff @developmentseed/range-reader shows a split.
Upgrading from the previous release
What to do.
- Move the four
@developmentseed/*peers to the versionnpm view @carto/ps-cog peerDependencieslists, all four in one install, from the 0.9 train to the 0.10 train.@deck.gl/*,@luma.gl/*,proj4and@cogeotiff/corekeep their ranges. - If you copied
colormaps.pngandlerc-wasm.wasmto your own host, copy both again fromnode_modules/@carto/ps-cog/dist/assets. The pinnedlercmoved in this release, and an old wasm still loads without an error. - Drop any
SourceHttp.fetchpatch from@chunkd/source-http. It no longer reaches any fileopenCogopens, see Credentials on reads.
No call into this package changes its shape, with three exceptions.
| Call site | Change |
|---|---|
| A mosaic renderSource that reads signal from its second argument | It gets { data, subLayerProps } and no signal, upstream stopped passing one. A TypeScript callback that destructures it no longer compiles |
| Code that reads layer.state.geotiff | Read layer.state.source.geotiff |
| MosaicTileLayer with maxCacheByteSize | Ignored with one warning per layer id, pass maxCacheSize, a count of sources |
A page that also builds upstream COGLayer or MosaicLayer by hand follows the upstream notes for those, source in place of geotiff and data in place of sources.
What behaves differently with no code change.
- A mosaic source that leaves the view frees its tiles and loads them again when it returns, so GPU memory stays flat on a long pan and a pan back costs range requests.
- Tile reads issued together merge into fewer range requests, see Byte and tile budget.
- A server or proxy that ignores
Rangefails the read withRangeIgnoredError, where the head of the file was decoded as a tile, see Errors. - EPSG:6933 resolves offline. A float LERC pixel the file marks invalid reads NaN, where it read 0.
- The inner tile layer of a
COGTileLayerorBandStackLayeris namedraster-tile-layer-<id>-<descriptor>-<refetch count>. The ids you set, mosaic sublayer ids andisCogLayerTreeMemberare unchanged. - Class breaks are new, see Render controls. Shared links written before this release read the same.
Bundler setup
Vite
// vite.config.ts
export default {
resolve: { dedupe: ["proj4", "@deck.gl/core", "@deck.gl/layers", "@luma.gl/core"] },
worker: { format: "es" },
assetsInclude: ["**/*.csv.gz"],
build: { target: "es2022" },
optimizeDeps: { rolldownOptions: { transform: { target: "es2022" } } },
};The optimizeDeps line is for Vite 8. On Vite 7 set the same target through optimizeDeps.esbuildOptions.target.
Other bundlers need the same four things. One resolved proj4 module, ES module workers, .csv.gz served as assets, and an ES2022 target. Never split deck.gl, luma.gl or loaders.gl across manual chunks, the app crashes at startup.
Shipped assets
The package ships the two binary files it loads at runtime, the colormap sprite and the LERC wasm.
| Export | File | Used by |
|---|---|---|
| @carto/ps-cog/assets/colormaps.png | Colormap sprite, one row per COLORMAP_INDEX entry | loadColormapSprite() |
| @carto/ps-cog/assets/lerc-wasm.wasm | LERC decoder wasm, the exact lerc version this package pins | LERC, LERC_DEFLATE and LERC_ZSTD tiles |
Core resolves both with a static new URL("../assets/<file>", import.meta.url), so most builds need no setup. loadColormapSprite() with no argument fetches the sprite, and a LERC tile loads the wasm on first use.
| Setup | What to do |
|---|---|
| Vite build, Rollup, webpack 5 | Nothing. Each emits both files, hashed like any other asset, and rewrites the URL. |
| Vite dev server with @carto/ps-cog installed from npm | Call configureCogAssets once at startup, as below. The dep optimizer moves core into node_modules/.vite, where the relative URL no longer finds the files. |
| esbuild, or any bundler that leaves new URL(..., import.meta.url) alone | Copy both files from node_modules/@carto/ps-cog/dist/assets to your static folder and call configureCogAssets with their URLs. |
| A CDN that rebuilds the package, such as esm.sh | Serve both files yourself and call configureCogAssets. |
| The prebuilt no bundler bundle on jsdelivr or unpkg | Nothing, see No bundler. |
import { configureCogAssets } from "@carto/ps-cog/cog";
import colormaps from "@carto/ps-cog/assets/colormaps.png?url";
import lercWasm from "@carto/ps-cog/assets/lerc-wasm.wasm?url";
configureCogAssets({ colormaps, lercWasm });The ?url suffix is Vite's. Elsewhere pass any URL that serves the file, a string or a URL. If you copy the files to your own host, copy them again on every upgrade of this package. A wasm from an older release still loads without an error, so a stale copy silently misses the decoder fixes of the pinned lerc. Call it before the first LERC tile decodes. lerc loads its wasm once per page, so a later call with a different lercWasm throws a CogAssetError, and a repeat call with the same URLs is a no op. Before handing the wasm to lerc, core checks that the URL answers with a wasm module. A dev server that answers index.html for a path it does not serve throws a CogAssetError of kind lerc-wasm that names the URL without its query, instead of the emscripten message "both async and sync fetching of the wasm failed". A wrong sprite URL throws one of kind colormaps.
configureLercWasm(url) still works and is deprecated, it forwards to configureCogAssets({ lercWasm: url }). The wasm override covers main thread decoding, the default. A worker DecoderPool passed as pool decodes LERC inside the worker with the upstream loader, which still looks beside its own chunk.
Quick start
import { type CogRendererInput, clampFitBounds, openCogRenderer } from "@carto/ps-cog/cog";
// Abort it on unmount or when the URL changes.
const controller = new AbortController();
const renderer = await openCogRenderer(url, { signal: controller.signal });
const cogLayer = (controls: CogRendererInput = {}) =>
renderer.layer(controls, {
onGeoTIFFLoad: (_, { geographicBounds }) => fitTo(clampFitBounds(geographicBounds)),
onTileError: console.error,
}).layer;openCogRenderer opens the file with the shared per-origin request limiter, loads the colormap sprite, reads the declared classes, the stats and the alpha band, and plans the tile loaders. renderer.layer(input, props) returns { layer, rendering }. input is a CogRenderState from parseCogRenderState in /params, whole or partial, merged over DEFAULT_COG_RENDER_STATE so { cmap: "magma" } draws magma, or the raw resolveCogRendering controls such as { colormapName: "magma" }. An input with a key only raw controls know is raw controls, and one that mixes such a key with a key only the render state knows (cmap with colormapName) throws a TypeError. The TypeScript union accepts such a mix, so this check only runs when layer() is called, pass one family per call. The layer id and getTileData are the same object across every render-only change (colormap, rescale, stretch, gamma, filter, nodata, palette), so deck.gl recompiles a shader or flips a uniform and refetches nothing. A band set not yet loaded gives a new id once. rendering carries legendDescriptor, availableModes, activeMode, kind and readContext for the UI.
| Option | Use |
|---|---|
| signal | Required. Abort it on unmount or a new URL, the open rejects with the signal's reason and builds no loader. |
| seed | The first render state, so a categorical preset on a file with no ColorMap opens on the loader its first paint uses. |
| stacDocs, href | STAC documents whose classification:classes win over the file's own GDAL classes. href is the STAC asset href of the file when it differs from url (a signed URL for an unsigned asset), url by default. |
| id | The layer id base, "cog" by default. |
| sprite | A colormap sprite already loaded, skips the sprite fetch. |
| presets | The category preset catalog, CATEGORY_PRESETS by default. |
| bandCount | The band count the plan's default band set is sized to, the file's own by default. The layer id equals the default one while bandCount is left out, equals the file's band count, or is four or more on a file of four or more bands, since the default band set stops at four. |
| onOpen | Called once the header is read, before the stats, with the file and its band plan for an interim layer. |
| onWarning | Each class skip and each render state value not applied, console.warn by default. |
| fetch, headers, renewal, concurrencyLimiter | As for openCog. |
A renderer from a file already open
import { createCogRenderer, MAX_LOADER_BANDS } from "@carto/ps-cog/cog";
// `geotiff` is open already, the picked source of openMosaicRepresentative,
// and `href` is that source's href.
const renderer = await createCogRenderer(geotiff, {
signal,
href,
stacDocs,
bandCount: MAX_LOADER_BANDS,
});
const { rendering, loader } = renderer.resolve(state);createCogRenderer(geotiff, opts) is the part of openCogRenderer past the open. It takes a GeoTIFF that is already open, a mosaic representative or a file from openCog, and never opens it again. It takes the same options except the openCog ones and returns the same CogRenderer, with the same decisions as openCogRenderer on that file, and the same layer id while bandCount is left out. href names the file, it is matched against stacDocs, gives the readout name and becomes renderer.url. Without it there is no STAC match and the readout keeps its default name. bandCount sizes the default band set of the plan, the file's band count by default, so a mosaic passes the widest sheet it may draw. A mosaic keeps its own MosaicTileLayer and draws with renderer.resolve(state).loader and .rendering, since layer() builds a single COGTileLayer.
A mosaic plans its loaders before any sheet opens with createCogBandPlan({ sprite, bandCount: MAX_LOADER_BANDS, id, categorical }), the same plan openCogRenderer makes, id "cog" and categorical false by default. Pass it to createCogRenderer as plan and the renderer draws with it and builds none of its own, so the layer id stays the mosaic's. id, bandCount and seed are then ignored.
One startup call
import { configureCog } from "@carto/ps-cog/cog";
import colormaps from "@carto/ps-cog/assets/colormaps.png?url";
import lercWasm from "@carto/ps-cog/assets/lerc-wasm.wasm?url";
configureCog({
assets: { colormaps, lercWasm },
epsg: async () => (await import("./more-crs.js")).table,
fetch: (url, init) => fetch(url, { ...init, credentials: "include" }),
});configureCog sets the shipped asset URLs, extra EPSG definitions and a default fetch or headers for every open that passes none of its own. Each key is optional and a key left out keeps what is set. A repeat call with equal values is a no op, so several modules may call it. A call with a different value replaces that setting for files opened later, files already open keep theirs, and reports a replaced warning that names the setting and never its value, through onWarning or console.warn. EPSG tables only add codes, a code already known keeps its first text and warns conflict. A different lercWasm after the first LERC tile still throws CogAssetError. A per open fetch or headers wins over the default and the two are never merged. fetch: null or headers: null clears that default. Default headers go to every origin a file opens on, so scope a credential to its host inside a fetch. The defaults belong to the module instance and apply to every open in the process, so on a server that renders for several users never put a per user credential in configureCog, pass it to each open.
Credentials on reads, migrating from a SourceHttp.fetch patch
Core reads COG bytes through openCog. A fetch or headers set per open or with configureCog reaches every range read of that file, the header, full resolution and overview tiles, stats samples, pixel readouts, mosaic sources, openCogRenderer, renewed reads and the open failure probe. Decoder workers only decode, they never fetch. A SourceHttp.fetch override from @chunkd/source-http is not supported. It is bypassed for every file openCog opens and never reaches the prebuilt browser bundle, which carries its own copy. Drop the patch and set the transport once at startup, adding the credential only on the origin that takes it.
import { configureCog, openCog } from "@carto/ps-cog/cog";
configureCog({
fetch: async (url, init) => {
const headers = new Headers(init?.headers);
if (new URL(url).origin === GATED_ORIGIN) {
headers.set("Authorization", `Bearer ${await currentToken()}`);
}
return fetch(url, { ...init, headers });
},
});
const geotiff = await openCog(url, { signal });Pass that GeoTIFF to COGTileLayer, never the URL string. A URL string is opened upstream through COGSource.open and skips the transport, and COGTileLayer warns once when it gets one while a default transport is set. A custom mosaic getSource that skips openCog opens the file itself, without the transport. STAC, mosaic JSON, VRT and GeoJSON index reads use the global fetch or the fetchJson of loadMosaicSources, and the colormap sprite and LERC wasm use the global fetch. Send a token in an Authorization header, never in the query. Where the storage only takes a query credential, sign the URL with @carto/ps-cog/signed-url and pass renewal to openCog.
Low level
The same render from the pieces openCogRenderer calls, for a caller that owns the sprite, the stats or the band plan.
import {
COGTileLayer, clampFitBounds, computeCogStats, DEFAULT_CONCURRENCY_LIMITER,
loadColormapSprite, makeMultiBandTileLoader, openCog, resolveAlphaBand, resolveCogRendering, type ResolveCogRenderingOptions,
} from "@carto/ps-cog/cog";
const signal = new AbortController().signal;
const geotiff = await openCog(url, { signal, concurrencyLimiter: DEFAULT_CONCURRENCY_LIMITER });
const [sprite, stats, alphaBand] = await Promise.all([
loadColormapSprite(),
computeCogStats(geotiff, signal),
resolveAlphaBand(geotiff, signal),
]);
const bands = [1, 2, 3].filter((b) => b <= geotiff.count);
if (alphaBand != null && !bands.includes(alphaBand)) bands.push(alphaBand);
const getTileData = makeMultiBandTileLoader(bands, { colormapSprite: sprite });
const cogLayer = (controls: Partial<ResolveCogRenderingOptions> = {}) =>
new COGTileLayer({
id: `cog:${bands.join(".")}`,
geotiff,
getTileData,
renderTile: resolveCogRendering(geotiff, { sprite, stats, alphaBand, ...controls }).renderTile,
onGeoTIFFLoad: (_, { geographicBounds }) => fitTo(clampFitBounds(geographicBounds)),
onTileError: console.error,
});COGTileLayerProps are the upstream layer props with the file given as geotiff, the GeoTIFF from openCog. Keep the same object across renders, a new one starts the tiles over, which is also how you swap the file, by a new layer, clone({ geotiff }) or a props spread. source takes an opened upstream COGSource instead, to share one between layers, and wins over geotiff when both are set. onGeoTIFFLoad(geotiff, info) fires once the layer has resolved the CRS and the tile grid of a geotiff, with info a CogGeoTIFFLoadInfo, { projection, geographicBounds }. It does not fire for a source that is already an opened COGSource. epsgResolver and concurrencyLimiter apply to a file the layer opens itself, a URL string, and are ignored for an opened one.
An unsigned integer COG, pixel-interleaved or band-separate, also renders with just new COGTileLayer({ id, geotiff }), with no rescale. A 4-band RGB file draws opaque unless its 4th band is tagged alpha, so NAIP-style NIR never turns into transparency.
Put it on a map
The layer is a plain deck.gl layer.
| Host | Add | Update |
|---|---|---|
| deck.gl | new Deck({ layers: [cogLayer()] }) | deck.setProps({ layers }) |
| MapLibre or Mapbox | map.addControl(new MapboxOverlay({ layers })) | overlay.setProps({ layers }) |
| React | <DeckGL layers={[layer]} /> | new layers prop |
| Google Maps | new GoogleMapsOverlay({ layers }) on a vector map | overlay.setProps({ layers }) |
Load @carto/ps-cog/cog with a dynamic import() to keep it out of the entry chunk. The Google Maps overlay reports a 0x0 viewport, so read the size from map.getDiv() before fitting bounds.
In a component framework, run one abortable load per URL, abort it on cleanup and drop results from a load that was replaced. React StrictMode runs effects twice. Create getTileData once per opened file, never during render. onGeoTIFFLoad fires again when the layer is rebuilt, so fit the camera once per URL.
No bundler
A plain HTML page loads the prebuilt bundle dist/browser/ps-cog.js through an import map, with no build step. The bundle is one ES2022 module with the whole root entry (every export of /cog, /params, /stac, /signed-url and /url, not /arrow). It inlines the @developmentseed raster train, @cogeotiff/core, lerc, flatbush, wkt-parser and @math.gl/*, and keeps bare imports of @deck.gl/core, @deck.gl/layers, @deck.gl/geo-layers, @deck.gl/mesh-layers, @luma.gl/core and proj4, which the page maps to the same copies it renders deck.gl with. The bundle finds the colormap sprite and the LERC wasm in dist/assets of the same package version on its own, so a page calls no configureCogAssets and loadColormapSprite() needs no URL. A copy of the sprite also sits beside the bundle as dist/browser/colormaps.png for pages that pass that URL. Licenses of the inlined packages are in dist/browser/THIRD_PARTY_LICENSES.txt. It is a file, not a package export, so a bundled app never picks it up.
The page below is rendered in headless Chromium against a LERC_ZSTD and a DEFLATE COG on every change and once a week. Save it as a file, serve the folder over HTTP and open it with ?url=<cog url>. To self host, copy dist/browser and dist/assets from the package into one dist folder and point the @carto/ps-cog entry at your copy.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ps-cog with no bundler</title>
<script type="importmap">
{
"imports": {
"@carto/ps-cog": "https://cdn.jsdelivr.net/npm/@carto/[email protected]/dist/browser/ps-cog.js",
"@deck.gl/core": "https://esm.sh/@deck.gl/[email protected][email protected]/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected]&target=es2022",
"@deck.gl/geo-layers": "https://esm.sh/@deck.gl/[email protected][email protected]/[email protected],@deck.gl/[email protected],@deck.gl/[email protected],@deck.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected]&target=es2022",
"@deck.gl/layers": "https://esm.sh/@deck.gl/[email protected][email protected]/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected]&target=es2022",
"@deck.gl/mesh-layers": "https://esm.sh/@deck.gl/[email protected][email protected]/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected],@luma.gl/[email protected]&target=es2022",
"@luma.gl/core": "https://esm.sh/@luma.gl/[email protected]?target=es2022",
"proj4": "https://esm.sh/[email protected][email protected]&target=es2022"
}
}
</script>
<style>
html, body { margin: 0; height: 100%; background: #fff; }
#map { position: relative; width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script type="module">
import {
COGTileLayer, clampFitBounds, computeCogStats, DEFAULT_CONCURRENCY_LIMITER,
loadColormapSprite, makeMultiBandTileLoader, openCog, resolveAlphaBand, resolveCogRendering,
} from "@carto/ps-cog";
import { Deck, WebMercatorViewport } from "@deck.gl/core";
// The package ships the colormap sprite and the LERC wasm, the bundle finds both with no call.
const url = new URLSearchParams(location.search).get("url")
?? "https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/36/Q/WD/2020/7/S2A_36QWD_20200701_0_L2A/TCI.tif";
const signal = new AbortController().signal;
const geotiff = await openCog(url, { signal, concurrencyLimiter: DEFAULT_CONCURRENCY_LIMITER });
const [sprite, stats, alphaBand] = await Promise.all([
loadColormapSprite(),
computeCogStats(geotiff, signal),
resolveAlphaBand(geotiff, signal),
]);
const bands = [1, 2, 3].filter((b) => b <= geotiff.count);
if (alphaBand != null && !bands.includes(alphaBand)) bands.push(alphaBand);
const deck = new Deck({
parent: document.getElementById("map"),
initialViewState: { longitude: 0, latitude: 0, zoom: 1 },
controller: true,
layers: [
new COGTileLayer({
id: `cog:${bands.join(".")}`,
geotiff,
getTileData: makeMultiBandTileLoader(bands, { colormapSprite: sprite }),
renderTile: resolveCogRendering(geotiff, { sprite, stats, alphaBand }).renderTile,
onGeoTIFFLoad: (_, { geographicBounds }) => {
const { west, south, east, north } = clampFitBounds(geographicBounds);
const viewport = new WebMercatorViewport({ width: innerWidth, height: innerHeight });
const { longitude, latitude, zoom } = viewport.fitBounds([[west, south], [east, north]]);
deck.setProps({ initialViewState: { longitude, latitude, zoom } });
},
onTileError: console.error,
}),
],
});
</script>
</body>
</html>The pins in this page are generated for @carto/ps-cog 0.18.0, the release this README ships with, and the deck.gl, luma.gl and proj4 versions its repository tests. Every release regenerates them, so for another version copy the page from that version's README.
- One instance of
@luma.gl/core,@deck.gl/coreandproj4per page. Two luma.gl copies break the shader module ABI, two deck.gl copies mix layer classes from two builds, and twoproj4registries split the definitions the library writes from the ones deck.gl-geotiff reads, so the COG renders black. That is why the bundle leaves them out. ImportDeck, andproj4if the page uses it, through the bare names of the map, never from a second URL. jsdelivr+esmbuilds load two luma.gl copies, so keep deck.gl, luma.gl andproj4on esm.sh. ?deps=pins the deck.gl graph. deck.gl and luma.gl import each other with^and~ranges, and esm.sh resolves each range on every request, so a patch release upstream would load a second copy next to the one the map names. With?deps=esm.sh builds the package against the listed exact versions and links the graph by exact build paths. Inside the graph esm.sh builds each package with only the listed packages it depends on, and that list is part of the build path, so each map URL carries exactly that list. A longer list loads a second build of the same version. The lists are generated and checked per release, so copy them as they are. Other dependencies such as loaders.gl and math.gl still float inside their ranges, self host the files for a page that never changes.- The page still loads deck.gl's own graph.
@deck.gl/geo-layerspulls loaders.gl, h3-js and more from esm.sh. The bundle needs it because the tile layers subclass it, and a page that renders deck.gl layers needs most of that graph anyway. - Workers are not covered. A worker needs a self contained entry, since import maps do not reach module workers, and the bundle keeps the upstream worker URL of
@developmentseed/geotiff. Decode on the main thread, the default, and pass nopool. - Browser support. Import maps and
import.meta.resolve, which the page uses to find the sprite beside the bundle, need Chrome 105, Firefox 108 or Safari 16.4.
Render controls
Rebuild the layer with the same id and getTileData. Only the shader or a uniform changes, no tile is fetched again.
import { computeExpressionStats, parseBandExpression } from "@carto/ps-cog/cog";
deck.setProps({ layers: [cogLayer({
colormapName: "magma", // any key of COLORMAP_INDEX
rescaleOverride: { min: 0, max: 3000 },
domain: "minmax", // or "percentile"
stretch: "sqrt", // "linear" | "sqrt" | "log"
gamma: 1.2,
bandFilter: [{ min: 10, max: 2000 }, null, null],
mode: "singleBand", band: 1, // or "rgb"
})] });
// band math through a colormap, the loader must hold every band it reads
const bandExpression = parseBandExpression("(b2-b1)/(b2+b1)")!;
const bandExpressionStats = await computeExpressionStats(geotiff, bandExpression, { signal });
cogLayer({ mode: "custom", bandExpression, bandExpressionStats });For a first paint or a catalog list that needs only a range, computeCogStats(geotiff, signal, { source: "stored-first" }) answers from the GDAL stored statistics with no tile request when every band has a stored min below its max, and samples otherwise. Its histograms are empty, so the render window is that min and max. mergeBandStats over only such results keeps their union range with an empty histogram. Mixed with sampled results, a stored-first range widens the merged range but adds no counts, so keep them apart when the histogram shape matters. readStoredStats(geotiff) returns the stored min, max, mean, std and validPercent per band, or null for a file without them.
computeCogStats says where its numbers came from. rangeSource maps each band to "header" when its min and max are the GDAL stored statistics, the range of the whole file, or "sample" when they are the range of the pixels read. sampleLevel is the level the histogram was sampled from, 0 for full resolution and n for overview n, and null when every band answered from the header with no sample. Without stored statistics the min and max come from the sampled level, not the file, and at an overview they are smoothed, so a sampled max can sit far below the file's true max. Show such a range as approximate, or read the band with computeCogWindowStats at level: 0 for exact values. Stats from mergeMosaicStats or computeBandStackStats carry neither field.
resolveCogRendering also returns legendDescriptor, availableModes and kind for your UI, and the decisions an app would otherwise re-derive. loaderNeeds is the band set and upload kind for CogBandPlan.select. readContext is the pixel readout context with the rendered kind, the sampled band or expression, the categories and the nodata to skip. statsTarget is the band, expression and nodata a stats read takes, with a key to memoize on and a bandKey without the nodata for a read that ignores it, or null in RGB. stretchStats is what the stretch window and its histogram read, the expression stats under band 1 in band math (null until computed) and stats otherwise, identity stable. resolveStretchStats(activeMode, stats, bandExpressionStats) is the same rule for stats the render did not read, a mosaic scan that widens the panel stats for one. singleBand is the band single band mode reads, band or 1. controls says which panel sections apply (stretch, filter, colormap, preset, palette, bands, bandMath, singleBand), and renderControlsFor computes the same from plain facts. An expression selects band math unless you pass expressionSelectsMode: false. Rebuild the loader, with a new id, only when loaderNeeds changes. Abort computeExpressionStats when the expression changes. Pass the same nodata override the layer renders with (null for off) so the ramp window leaves out the pixels the map leaves out. computeBandStackExpressionStats takes the same nodata and applies it to every file of the stack.
The internal mask and the nodata value follow the stats rule. A pixel the file's internal mask marks empty never draws, nodataOverride: "off" included, since "off" drops only the nodata value and the float NaN guard. Band math discards a pixel when any band it reads is nodata, single band and categorical renders test their one band, and RGB discards only when all three bands read nodata. NaN parts from the stats, which always skip a non-finite value, in two cases. Under "off" a NaN pixel on a float COG draws. In RGB a pixel draws unless all three bands are NaN. A custom renderTile over makeMultiBandTileLoader gets no mask for free, it binds data.mask with upstream MaskTexture itself.
Class breaks
A continuous band painted in discrete classes, exact at every edge. Use it when the band holds a score or a measure and the map must show classes, a risk score in six levels for one. A colormap cannot do that, it rescales the band and samples a ramp with linear filtering, so a value on a class edge draws a colour no class has. A categorical render cannot either, it needs an 8 bit band of class codes.
import { type ClassBreaks, classBreakColor, classBreakIndex } from "@carto/ps-cog/cog";
const classBreaks: ClassBreaks = {
edges: [0, 50, 150, 250, 350, 400], // n + 1 ascending edges, in the units the file STORES
colors: [[255, 255, 178], [254, 204, 92], [253, 141, 60], [240, 59, 32], [189, 0, 38]],
aboveColor: [122, 1, 119], // optional, nothing is drawn above the last edge without it
labels: ["Negligible", "Low", "Moderate", "High", "Extreme"], // optional, legend and readout
};
deck.setProps({ layers: [cogLayer({ mode: "singleBand", band: 1, classBreaks })] });
classBreakIndex(150, classBreaks); // 2, an edge opens its class, so 150 is Moderate
classBreakColor(400, classBreaks); // [189, 0, 38, 255], the last class is closed on both endsClass i holds [edges[i], edges[i + 1]) and the last class also holds its upper edge. A value below the first edge draws belowColor, a value above the last one aboveColor, and nothing when the colour is left out. NaN never draws. A colour is RGB or RGBA in whole numbers from 0 to 255, alpha 255 when left out, and a colour with alpha 0 draws nothing, which is how you hide a class. edges and each colour may be a plain array or a typed array, a Float64Array of quantiles or a Uint8Array colour. At most MAX_CLASS_BREAKS classes, 32. labels are yours, the library passes them to the legend and the readout and never writes one, and an empty label reads as no label. Treat a table as immutable and build a new object to change it, a table that passed the guard is not walked again.
Edges are in stored units. They are the numbers the file stores, before any scale or offset the file declares, the same units as nodataOverride and bandFilter. A file that stores a score times 100 in INT16 with a GDAL scale of 0.01 takes edges: [0, 50, 150, ...], not [0, 0.5, 1.5, ...]. The readout prints the value after scale and offset (1.5), so each legend entry carries both, min and max in stored units and displayMin and displayMax after scale and offset. Print the display ones and the legend agrees with the readout. They are equal when the file declares no scale and offset.
Values and edges are compared as 32 bit floats, the precision a tile holds on the GPU, so a float32 pixel of 0.1 sits on an edge written 0.1. classBreakIndex and classBreakColor are that rule in JS, 0 to n - 1 for a class, -1 below, n above and null for NaN. A float32 value smaller than the smallest normal float (about 1.18e-38) may read as 0 on a GPU that flushes subnormals.
classBreaks applies in single band mode, on a single COG, a band stack and a mosaic alike. resolveCogRendering then reports kind: "classBreaks", while detectedKind still says what the file is, and returns a legendDescriptor of kind "classBreaks".
| Field | Meaning |
|---|---|
| entries | One entry per class that draws, in edge order, { index, min, max, displayMin, displayMax, maxInclusive, color, label? }. A class hidden with alpha 0 has no entry, so index skips it. color is RGBA, keep its alpha in your swatch |
| above, below | The colour drawn past the last edge and before the first one, null when the map draws nothing there, a colour with alpha 0 included |
| range | { min, max, displayMin, displayMax }, the first and the last edge of the table, for the above and below rows |
| filter | The active keep range in stored units, or null |
| band | The 1-based band the classes read |
The display bounds come from the scale and offset the file declares for the band. For a band stack the band lives in another file, so pass classBreaksDisplay: bandStackDisplayTransform(stack, band) to resolveCogRendering.
The readout row of formatCogReadout carries classIndex, classLabel and the class colour as swatch, read from the stored value, next to the printed display value. controls turns off the stretch, the colormap, the preset and the palette, none of them changes a pixel under class breaks. Nodata still discards. The keep range (bandFilter) still discards too, and under class breaks it is tested by the class shader on the same value the classes read, in stored units with both bounds kept, so it is exact on an 8 bit band as the edges are. A value the keep range discards has no classIndex and no swatch in the readout, it is not on the map. In rgb or custom mode the mode renders and classBreaksWarnings holds one class-breaks-not-applied entry, which a CogRenderer sends to onWarning. A table that breaks a rule throws a RangeError that names the field and says what it received, when the render is resolved, never per tile. Run assertClassBreaks(breaks) to check one yourself.
A new table flips uniforms. It never recompiles the shader, never refetches a tile and keeps the layer id, so a slider over the edges is cheap, and so is a new keep range. Turning class breaks on or off recompiles the shader once and still refetches nothing.
To own the layer wiring, buildClassBreaksRenderTile({ classBreaks, band, nodataOverride, bandFilter }) returns the renderTile for a loader from makeMultiBandTileLoader. Its pipeline is the band composite, the hole modules and ClassBreakColors, the shader module, whose uniforms classBreaksProps(breaks, sampleScale, keepRange) builds, the same object for the same inputs. classBreakEntries(breaks, { scale, offset }) gives the legend rows on their own. A helper that derives breaks from data, quantiles of computeCogStats for one, only has to return a ClassBreaks.
import { buildClassBreaksRenderTile, COGTileLayer, makeMultiBandTileLoader } from "@carto/ps-cog/cog";
const layer = new COGTileLayer({
id: "risk",
geotiff,
getTileData: makeMultiBandTileLoader([1]),
renderTile: buildClassBreaksRenderTile({
band: 1,
classBreaks: { edges: new Float64Array([0, 1.5, 4]), colors: [[255, 255, 178], [189, 0, 38]] },
}),
});Band plan
neededBands, TileLoaderRegistry and layerIdForBands encode rules 2 and 3 below, so a control change keeps the loader and the id and only a band that is not loaded yet refetches.
import {
COGTileLayer, defaultLoaderBands, layerIdForBands, makeMultiBandTileLoader, neededBands,
resolveCogRendering, TileLoaderRegistry,
} from "@carto/ps-cog/cog";
// once per opened file
const defaults = defaultLoaderBands(geotiff.count);
const loaders = new TileLoaderRegistry(defaults, (b) =>
makeMultiBandTileLoader(b, { colormapSprite: sprite }));
// on every control change
const r = resolveCogRendering(geotiff, { sprite, stats, alphaBand, ...controls });
const loader = loaders.ensure(neededBands({
bandCount: geotiff.count, activeMode: r.activeMode, kind: r.kind, alphaBand,
bands: controls.bands, singleBand: controls.band, bandExpression: controls.bandExpression,
}));
new COGTileLayer({
id: layerIdForBands("cog", loader.bands, defaults),
geotiff,
getTileData: loader.getTileData!, // null only for a registry built with a null factory
renderTile: r.renderTile,
});ensurereturns the sameTileLoaderobject while its bands cover the need, sogetTileDatastays stable and the id stays the barebaseIdfor any file with at most four bands.- A band outside
1..bandCountis dropped, and a need with no valid band falls back todefaults, so a bad control value never yields a bandless tile. CogBandPlanwraps the above for one opened file, with a second registry for the categorical upload.new CogBandPlan("cog", geotiff.count, (bands, categorical) => makeMultiBandTileLoader(bands, { colormapSprite: sprite, categorical })), paintplan.current, then on every control change passplan.select(resolved.loaderNeeds)to the layer asidandgetTileData. A categorical upload rides under<baseId>:categorical, so picking a preset on a file with no ColorMap, or dropping it again, refetches instead of keeping the old tiles. A file with its own ColorMap never asks for that upload, so a palette toggle keeps every tile. Seed the kind the link opens with,new CogBandPlan("cog", geotiff.count, make, { categorical: seedCategoricalUpload(state, ctx, { hasFileColorMap, bandCount: geotiff.count }) })withseedCategoricalUploadfrom/params, soplan.currentis the loader the firstselectreturns and the first tiles are fetched once.PlannedLoader.categoricalis the upload kind, pass it to aBandStackLayer. The two argumentselect(neededBandsInput, categorical)is deprecated.- For a band-math builder,
selectableFormulaBands(formula, bandCount)from/paramsoffers every band until the formula reads four distinct bands, then only those.formulaBandslists the bands a formula reads.appendFormulaToken,removeFormulaTokenandcycleFormulaOpedit a chain, andnormalizeFormulagives what to write toexpr, or null to delete it. - When your layer id is fixed by something else (a layer store that sets
idto its own key), keep the id and passupdateTriggers: { getTileData: bandSetKey(loader.bands) }instead, orplanned.idfromCogBandPlan, which also tells the upload kinds apart.COGTileLayerandBandStackLayer(whose band set isbandIndexes) turn a change of that trigger into a fresh tileset under the sameid, every tile is fetched again with the new bands and the old tiles' textures are freed. A trigger that stays the same across a control change keeps every tile.BandStackLayeralso refetches whenbandIndexeschanges as a set, trigger or not. The new tileset starts empty, so the layer shows nothing until the first tiles of the new band set decode, the same as with a newid. ChanginggetTileDataorbandIndexeswith neither a newidnor a new trigger keeps the cached tiles on the old bands, and a render that asks for a band a tile does not carry falls back to its first band. isMosaicSublayerId("cog", layer.id)matches the id shape of a per-source sublayer of a mosaic under that id. It reads the id string alone, so a foreigncog-2020layer matches too. Route a deckonErrorwithisMosaicSublayerTreeMember, which also needs the root layer above it.mosaicSublayerId("cog", source)is the idMosaicTileLayerandbuildMosaicRenderSourcegive a per-source sublayer,<id>-<source.id>, or<id>-<key>frommosaicSourceKey(source.href)when the source has noid. Use it in a customrenderSourceso your ids matchisMosaicSublayerId. The key is the href with its query, fragment and userinfo dropped, plus~<hash>of the query parameters that are not a signature (X-Goog-*,X-Amz-*, an Azure SAS,Signature,Expires,AWSAccessKeyId,token,access_tokenand the like). The query starts at the first raw or encoded?, the same cutredactUrlmakes, and a fragment never feeds the key. So?file=a.tifand?file=b.tifget two ids, a signed href never reaches a layer id, and the id holds across a token refresh that only re-signs the href.
Controls and URL state
@carto/ps-cog/params is the shared grammar for render state in a query string. Every control has a parse*Param that never throws and falls back to the default, and a serialize*Param that returns null for the default so it stays out of the URL. It loads no deck.gl, luma.gl, @developmentseed, geotiff or proj4 code at runtime, so it is safe in an entry chunk. Its type declarations still reference @developmentseed types, so a type-checking consumer keeps the peers installed or sets skipLibCheck.
import {
clearStretchWindowParams, encodeFormula, filterToPerBand, normalizedDifference, parseBandsParam,
parseColormapParam, parseCurveParam, parseExprParam, parseFilterParam, parseGammaParam,
parseModeParam, parseNodataParam, parseRescaleParam, parseRgbStretchParam, pinStretchWindow,
serializeCurveParam,
} from "@carto/ps-cog/params";
const q = new URLSearchParams(location.search);
cogLayer({
mode: parseModeParam(q.get("mode")) ?? undefined, // null lets the file kind pick
bands: parseBandsParam(q.get("bands")),
colormapName: parseColormapParam(q.get("cmap")),
rescaleOverride: parseRescaleParam(q.get("vmin"), q.get("vmax")),
perBandRescale: parseRgbStretchParam(q.get("rgbStretch")),
stretch: parseCurveParam(q.get("curve")),
gamma: parseGammaParam(q.get("gamma")),
bandFilter: filterToPerBand(parseFilterParam(q.get("fmin"), q.get("fmax"))),
nodataOverride: parseNodataParam(q.get("nodata")).override,
bandExpression: parseExprParam(q.get("expr")) ?? undefined, // base64url, or infix "(b4-b3)/(b4%2Bb3)" in a URL
});
const curve = serializeCurveParam("sqrt");
if (curve == null) q.delete("curve"); else q.set("curve", curve);
q.set("expr", encodeFormula(normalizedDifference(4, 3)));
clearStretchWindowParams(q); // a new band or expression invalidates vmin, vmax, rgbStretch, fmin, fmax
pinStretchWindow(q, autoWindow); // before copying a share link, so a mosaic rescan cannot drift itA number param that is blank or not finite reads as absent, never as 0. Written bounds keep three decimals at 1 and above and three significant digits below, so a small float window survives a round trip. parseExprParam returns null for an expression over four distinct bands or longer than MAX_EXPR_PARAM_LENGTH, and an infix + in a URL must be sent as %2B.
| Param | Codec |
|---|---|
| mode, band | parseModeParam, parseSingleBandParam |
| bands, rgbStretch | parseBandsParam, parseRgbStretchParam |
| vmin, vmax | parseRescaleParam, serializeRescaleBound, pinStretchWindow |
| fmin, fmax | parseFilterParam, serializeFilterMin, serializeFilterMax, filterToPerBand |
| cmap | parseColormapParam, serializeColormapParam |
| domain, curve, gamma, maxError | parseDomainParam, parseCurveParam, parseGammaParam, parseMaxErrorParam |
| expr | parseExprParam, encodeFormula, decodeFormula, presetFormula, defaultPresetBands |
| breaks, breakColors, breakAbove, breakBelow, breakLabels | parseClassBreaksParams, serializeClassBreaksParams, CLASS_BREAKS_PARAM_KEYS |
| preset, palette, nodata, inspect | parsePresetParam, parsePaletteParam, parseNodataParam, parseInspectParam |
| stats-scope, stats-refresh, stats-cap, area-scope | parseStatsScopeParam, parseStatsRefreshParam, parseStatsCapParam, parseAreaScopeParam |
| url | parseUrlParams, setUrlParams, splitUrlInput, joinUrls |
maxError is the reprojection mesh error in output pixels, measured on the map. It used to count source pixels, so the same value can now draw a finer or coarser mesh. The default and the clamps are unchanged.
The defaults (DEFAULT_COLORMAP, COLORMAP_NAMES the colormap names the /cog sprite holds, DEFAULT_DOMAIN, DEFAULT_CURVE, DEFAULT_GAMMA, DEFAULT_MAX_ERROR, DEFAULT_BANDS, DEFAULT_STATS_CAP) and clamps (MIN_GAMMA, MAX_GAMMA, MIN_MAX_ERROR, MAX_MAX_ERROR, MAX_STATS_CAP, MAX_EXPR_PARAM_LENGTH) are exported, never hard-code them. So are the value lists DOMAIN_MODES, STRETCH_CURVES, INSPECT_MODES and the gamma slider step GAMMA_STEP. COG_PARAM_SPECS maps every state key to its kind, values, default and range, with no display string, so a help page or a picker reads the grammar instead of restating it. COG_STATE_PARAM_KEYS lists every key, and clearCogStateParams wipes them when a new file loads. STRETCH_WINDOW_PARAM_KEYS is the subset clearStretchWindowParams drops. The clear helpers mutate and return the instance you pass, so pass a copy if you need the old one. A shared link is only as stable as this grammar, so a change to a name, default or clamp ships as a minor release with a changelog note.
Class breaks take five params that read as one table. breaks is the comma separated edges in stored units, written in full and never rounded. Each edge is a decimal number with an optional sign, fraction and exponent (-2.5, .5, 1e3). Hex, binary and octal forms, an empty item and an item of only spaces are rejected. breakColors is one rrggbb or rrggbbaa hex per class, with no #. breakAbove and breakBelow are one hex each, and breakLabels is one label per class, each percent encoded so a label may hold a comma. parseClassBreaksParams returns null when breaks or breakColors is absent, and also when an edge or a colour is malformed, a value is over its cap or the table fails assertClassBreaks, so a link never draws half a table. The caps are MAX_BREAK_EDGES edges, MAX_BREAKS_PARAM_LENGTH and MAX_BREAK_COLORS_PARAM_LENGTH characters, checked before the value is split. Labels never cost the table. Labels over MAX_BREAK_LABELS_PARAM_LENGTH (counted on the percent encoded text, so one character outside ASCII costs up to nine), with a stray percent sign or with a count that is not the class count are left out and the table is kept. serializeClassBreaksParams applies the same count and leaves such labels out, so what it writes always reads back with the same edges and colours. A list of only empty labels is no labels on both sides.
Whole render state
Prefer the one call codec over the per param ones, so two consumers can never read a link differently. parseCogRenderState(q, { colormaps, onWarning }) reads every render param into one CogRenderState, serializeCogRenderState writes it back, and cogRenderStateKey gives a canonical string to memoize on, empty for the default state. isDefaultCogRenderState(state) is true when that key is empty, so no app compares a state to the defaults by hand. Check the state, not the renderStateToOptions object, which always carries the default values. patchCogRenderParams(q, patch) returns a new URLSearchParams with only the patched keys written, and clears STRETCH_WINDOW_PARAM_KEYS when mode, band, bands or expr changes. A window is in the data units of the band or expression it was drawn on, so it means nothing once the subject moves. expr moves only when the expression does, so the same expression written as infix in the link and patched as a compact formula (or the reverse) keeps the window. To keep it, write rescale, rgbStretch or filter in the same patch, they are set after the clear. parseCogInspectorState, serializeCogInspectorState, cogInspectorStateKey and patchCogInspectorParams do the same for inspect, stats-scope, stats-refresh, stats-cap and area-scope. COG_RENDER_STATE_PARAMS and COG_INSPECTOR_STATE_PARAMS map each field to its keys, and DEFAULT_COG_RENDER_STATE and DEFAULT_COG_INSPECTOR_STATE are the empty link.
Window bounds are rounded the way they are written, three decimals at 1 and above, three significant digits below. A narrow window such as fmin=0.10001&fmax=0.10002 keeps the digits that hold it open. An inverted or empty filter is dropped and reported as empty-filter. state.classBreaks is the class table of the five break* params or null, and a table that does not validate is dropped and reported as invalid-class-breaks. Labels that cannot be used are left out of a table that is kept and reported as invalid-break-labels. parseCogRenderState always sets the field, and it is optional on the type, so a state built by hand before it existed still type checks and reads as no class breaks. The value a warning echoes from a link is cut to MAX_WARNING_VALUE_LENGTH characters. A mode or band patch keeps it, a class table follows the dataset, and clearCogStateParams removes it with every other state param when a new file loads.
renderStateToOptions(state, ctx?) shapes a state into the resolveCogRendering options a link decides. expr is forwarded only under mode=custom, a lone vmin or vmax is a one sided window (the given bound pinned, the other from the auto domain), and paletteSource is sent only with a resolved preset. An unknown cmap renders as the default with a warning. ctx.colormaps sets the names it checks against and defaults to COLORMAP_NAMES, so the check runs with no ctx too. An absent cmap reads as DEFAULT_COLORMAP, so a picker that offers an Auto colormap shows it when state.cmap equals DEFAULT_COLORMAP. A categorical file never reads cmap, its auto palette is preset auto with palette file, both the defaults. Leave ctx out for a readout or stats read, no preset is then applied. Skips arrive on onWarning as a ParamWarning with a kind of unknown-colormap, expr-not-custom, preset-unavailable or empty-filter, a param and the skipped value. bandExpressionKey(expr) is a content key for a band expression, memoize a stats scan on it rather than on the object, which is new after every render change. nodataForRead(state.nodata) is the nodata a readout, stats read or legend skips, and it takes the ParsedNodata from parseNodataParam too, off giving null. needsCategoricalUpload({ preset, hasFileColorMap }) says whether the index band needs a nearest sampled upload. seedCategoricalUpload(state, ctx, { hasFileColorMap, bandCount }) gives the upload kind to open with before any stats, the same answer loaderNeeds.categoricalUpload gives once the file resolves. exprFromFormula(formula) builds the expr field for a patch.
import { resolveCogRendering } from "@carto/ps-cog/cog";
import { parseCogRenderState, patchCogRenderParams, renderStateToOptions } from "@carto/ps-cog/params";
const state = parseCogRenderState(q, { onWarning: console.warn });
const rendering = resolveCogRendering(geotiff, {
sprite,
stats,
...renderStateToOptions(state, { ...presetCtx, onWarning: console.warn }),
});
const next = patchCogRenderParams(q, { mode: "rgb" }); // write next to the address barPresets
preset is auto when absent, none, stac, gdal or a catalog slug. PRESET_AUTO, PRESET_NONE, PRESET_STAC, PRESET_GDAL and RESERVED_PRESET_SLUGS name the reserved values, no catalog key uses one. auto applies only the classes the source declares, STAC classification:classes first, then the GDAL CLASSES item, and only when they can paint every class. A catalog preset the file's codes and colours fit is a suggestion, shown in the picker and never applied unless picked.
buildPresetContext({ declared, suggested, catalog, classable }) turns one load's facts into a PresetContext. Pass the result of resolveDeclaredClasses as declared, suggestCategoryPreset(geotiff)?.slug as suggested, CATEGORY_PRESETS as catalog and metadata.classable as classable. The merged presets record keeps its identity across rebuilds. resolveSelectedPreset(selection, ctx, ctx.presets) gives the preset to pass as categoryPreset, undefined for none, an auto with nothing declared that paints, or a slug the context does not hold. The positional form from /cog, resolveSelectedPreset(selection, autoSlug), still works and is deprecated.
presetPickerModel(state, { ...ctx, hasFileColorMap }) is everything a picker shows, as keys and kinds (auto, none, declared, suggested, catalog, unavailable), never display strings. When auto resolves to numeric labels, none would paint the same and is left out unless it is the selection, so a ?preset=none link still shows selected. A selection the context lacks is listed last and disabled, so value is always an option. autoResolvesTo names the declared slug auto applies, effective the preset that paints, showPalette whether a palette toggle changes a pixel, and enabled is false on a source that is not classable while the selection is auto.
import { CATEGORY_PRESETS, resolveDeclaredClasses, suggestCategoryPreset } from "@carto/ps-cog/cog";
import { buildPresetContext, presetPickerModel, resolveSelectedPreset } from "@carto/ps-cog/params";
const ctx = buildPresetContext({
declared: resolveDeclaredClasses({ metadata, geotiff, stacDocs, href }),
suggested: suggestCategoryPreset(geotiff)?.slug ?? null,
catalog: CATEGORY_PRESETS,
classable: metadata.classable ?? false,
});
const categoryPreset = resolveSelectedPreset(state.preset, ctx, ctx.presets);
const picker = presetPickerModel(state, { ...ctx, hasFileColorMap });Read palette with parsePaletteParam(q.get("palette")) and pass it as paletteSource, or let renderStateToOptions do it. file, the default, keeps an embedded ColorMap and takes only labels from the preset. preset paints the preset colours over it. A change is a texture swap, never a refetch.
Inspector helpers
Pure helpers in /cog that return plain data, so any chart or legend kit can use them.
- Histogram
histogramEdges(n + 1 edges),histogramBinLabels. For a brush,windowToSelectedBarshighlights the current window andselectedBarsToWindowturns brushed bars into arescaleOverride. - Metadata
metadataRowswith a stablekeyper row, label rows from it in your own strings (labelis deprecated, anunsetrow has no value),fileBasename,bandOptionName(the file name behind a stack band, null for a plain band).bandOptionLabelis deprecated. - Legend
legendNumber,shadeLegendRamp(dims stops outside a filter),rgbChannelItems({ channel, band, color }per display channel, labelchannelyourself),rgbChannelLegend(pass your ownlabels, its English default is deprecated),CHANNEL_COLORS,RGB_CHANNELS(red,green,blue, label them yourself),rgbToHex,hexToRgb.CHANNEL_LABELSis deprecated. - Rescale
resolveBandRescaleSource(stats, band, override, domain)returns{ window, source },sourceisoverride(both bounds set),partial(one bound set, the other filled from the auto domain thatfillnames,percentileorminmax),percentileorminmax, so a panel marks a custom window without restating the rule. A lone bound that would cross the auto bound on the other side is not applied. The result then keeps its autosourceand window and carrieswarning, aBandRescaleWarningof kindrescale-bound-crossedwith theband, thebound(minormax), the ignoredvalueand the drawnwindow. Two bounds withmin >= maxare not applied either, the warning is then of kindrescale-window-invertedwith the givenminandmaxand the drawnwindow, the auto one, or{ min: 0, max: 1 }in a render tile with no stats (the resolver itself returns null there).BandRescaleWarningis the union ofBandRescaleBoundWarningandBandRescaleInvertedWarning, so switch onkind.resolveCogRenderingcollects them inrescaleWarningson every call, thebuild*RenderTilefactories takeonRescaleWarning, and aCogRenderersends each toonWarningonce while the same band, bound and value stay crossed. A NaN or infinite bound counts as not set. The legend'sdomainSourcereadspartialfor a one sided window. A lone bound with no stats returns null, there is no domain to fill from yet. - Window levels
summarizeWindowLevels(windows)returns{ kind, lo, hi, canForceLevel0 }for one or more window reads,kindisnone,exact,overview,subsampledorestimate(a band stack file read from its own overview), with the same rule asexact. - Colormaps
colormapGradient(sprite, COLORMAP_INDEX[name])returns a CSS gradient for a picker. It throws on a row outside the sprite.colormapGradientByName(sprite, name)takes the name instead and returns null for a sprite still loading, an unknown name or a missing row, so a name straight from the URL is safe. - Errors
isAbortErrorfor the error an aborted read throws. It also matches an error whosecausechain holds the AbortError, such as theSourceErrora cancelled range fetch rejects with, so check it rather thanerr.name.
Categorical rasters
Presets ship for nlcd, esa-worldcover, io-lulc, sentinel2-scl, dynamic-world, globeland30, cfmask, koppen-geiger, modis-igbp, cgls-lc100, jrc-gsw-transitions, esa-cci-lc, glc-fcs30d, corine and usda-cdl.
import {
CATEGORY_PRESETS, makeMultiBandTileLoader, matchCategoryPreset, observedCategoryCodes,
observedCategoryColors,
} from "@carto/ps-cog/cog";
const match = matchCategoryPreset(observedCategoryCodes(geotiff), CATEGORY_PRESETS, {
colors: observedCategoryColors(geotiff),
});
const categoryPreset = match?.preset ?? CATEGORY_PRESETS["esa-worldcover"];
const getTileData = makeMultiBandTileLoader([1], { colormapSprite: sprite, categorical: true });
// pass { categoryPreset } to resolveCogRenderingUse categorical: true when the file has no embedded ColorMap, so classes are sampled nearest. Build your own preset with defineCategoryPreset.
readCategories(geotiff, preset?, { nodata, paletteSource }) lists the legend classes. The nodata code is never a class, whatever its slot colour. A TIFF ColorMap carries no alpha, so colour is the only signal. An embedded ColorMap slot that is not black is a class. A black slot is a class only when it stands alone, with a painted or nodata slot on each side, and for a code the preset names the table edge also counts as a side. Every other black slot is padding, so the zero-filled rows of a 256-slot table are left out. nodata follows the render override, a number replaces the file value and null stands for nodataOverride: "off". resolveCogRendering passes it to the legend for you, buildLegendDescriptor takes the same nodata option and never adds the nodata code back from observedCodes. observedCategoryCodes returns the painted codes minus nodata, for preset matching, so the legend may list a lone black class the matcher does not see. observedCategoryColors returns the file colour of each of those codes. Pass it as colors and a preset that colours the present codes must agree with the file palette on at least three quarters of them, each channel within 24, or it is not a match. Codes alone accept any short run such as 1 to 33 for every preset keyed 1 to N, so without colors an FAO agro-ecological zones file matches CORINE.
By default an embedded ColorMap paints the classes and the preset only names them. Pass paletteSource: "preset" to resolveCogRendering to paint the preset colours instead. Each code the preset colours takes its colour, a code it has no colour for keeps the file colour, and the legend shows the same merged colours. palette on the result is that merged LUT. To build one yourself, buildMergedPaletteImage(file, classes) takes the file ColorMap LUT and a preset classes record, and returns a new ImageData with each coloured class painted over its slot at full alpha, leaving the file palette untouched. resolveCogRendering builds and memoizes this LUT for you, so prefer it. Otherwise first ask hasEmbeddedColorMap(geotiff) or readCogMetadata(geotiff).hasColorMap whether the file has a ColorMap at all, then parse the file ColorMap once per file with parseColormap from @developmentseed/geotiff, the dependency openCog uses. A class code that is negative, not an integer, or at or past the width of file is skipped without an error, while buildPaletteImage throws for a code outside 0 to 255. The palette texture cache keys on the returned ImageData object, so a fresh build each render uploads a new texture. Memoize it per file palette and preset, as resolveCogRendering does. The nodata code stays a hole and is never a class. Switching paletteSource binds another palette texture inside renderTile, it never refetches a tile, so keep the layer id as it is. Without a ColorMap in the file, or without a preset, both values render the same.
STAC classification classes
A STAC item can describe its classes with the Classification extension, v1.x or v2.0. pickStacClasses(source, { asset, band, onWarning }) finds the classification:classes list for one band of an item, a collection, an asset or a bare band object, and returns { classes, nodata, dataType, from } or null. band is 1-based and defaults to 1. A named asset is the only asset read, and a name the source does not have returns null with a missing-asset warning. Without one the pick is the first asset that carries classes among the COG data asset (data, visual, image, rendered_preview, then any GeoTIFF with the data role) and every other data role asset, skipping a non-GeoTIFF media type and the overview and thumbnail roles, so a PNG preview never hides the classes on the COG. An asset with the visual role and no data role is skipped too. The roles decide this, not the asset key, so an asset under the visual key with no roles is still read. A collection picks from item_assets the same way. The lookup order is below, the first list found wins.
| Source | Order |
|---|---|
| Asset with a STAC 1.1 bands list | bands[i], the asset level, then raster:bands[i] |
| Asset without bands | raster:bands[i], then the asset level |
| Item, after its asset | properties.bands[i] when that list matches the asset band count, then properties |
| Collection, after its assets | the item_assets entry picked by the same asset rule |
nodata and dataType come from the object that held the list, else from its asset or band. Classes on the item properties take them from the picked asset, its bands[i], its raster:bands[i], then the asset level. An empty or non-numeric nodata string reads as no nodata, nan and inf read as NaN. Only classification:bitfields yields null with a bitfields-only warning.
categoryPresetFromStacClasses(classes, { name, nodata, dataType, onWarning }) turns the list into a CategoryPreset, or null when nothing usable is left. A class flagged nodata: true and a class at the band nodata are left out. A flagged code goes to preset.nodataCodes and blocks a later class with the same value, and readCategories and buildLegendDescriptor never list a nodataCodes entry, so a flag off the band nodata never shows up as Value 255. The render mask still follows the file nodata or nodataOverride. The label is title, then name, then description, then Value <code>. color_hint (the v1 spelling color-hint too) is RRGGBB, any case, with an optional leading #. A class without a hint carries only its label. Each call returns a new preset, and the palette LUT is cached per preset object, so build it once per item and keep it, or every render uploads a new palette texture. Malformed entries are skipped and reported to onWarning as a StacClassWarning with a code, bad-hint, alpha-hint (an 8 digit hint, the label is kept), bad-value (not an integer in 0 to 255), duplicate-value (the first wins), nodata-mismatch (a nodata: true class off the band nodata), nodata-value, float-band (a float b
