Skip to content

feat: Titiler .npy tile example with RasterTileLayer - #469

Closed
kylebarron wants to merge 10 commits into
mainfrom
titiler-example
Closed

kylebarron wants to merge 10 commits into
mainfrom
titiler-example

Conversation

@kylebarron

@kylebarron kylebarron commented Apr 24, 2026 •

Copy link
Copy Markdown
Member
image

Validated that this does render from titiler.xyz

Closes #461

Summary

  • New example at examples/titiler-cog/ that renders tiles fetched from titiler.xyz as .npy numpy arrays, decoded client-side and drawn via RasterTileLayer.
  • First example in the repo that uses RasterTileLayer directly (not via COGLayer / ZarrLayer). Demonstrates the flow for any server that hands back per-tile binary arrays for an OGC tile matrix set.
  • Startup fetches /cog/WebMercatorQuad/tilejson.json (WGS84 bounds + min/max zoom) and /tileMatrixSets/WebMercatorQuad (tile pyramid). Builds a TileMatrixSetAdaptor with identity EPSG:3857 projections and proj4-backed EPSG:4326 projections, injects a boundingBox on the TMS, and fits the map to the dataset bounds.
  • Per tile: fetch .npy → decode with npyjs → repack band-separate uint8 (B, H, W) to interleaved RGBA → upload RGB texture + optional r8unorm mask texture → pipeline CreateTexture + MaskTexture.

Design doc: dev-docs/specs/2026-04-24-titiler-cog-example-design.md.

Test plan

  • pnpm --filter deck.gl-titiler-cog-example dev renders the Sentinel-2 TCI RGB tiles over the dark basemap and fits the map to the scene.
  • Zooming and panning loads new tiles from titiler.xyz.
  • "Show Debug Mesh" toggle + "Debug Opacity" slider behave the same as in other examples.
  • pnpm --filter deck.gl-titiler-cog-example typecheck passes.
  • pnpm --filter deck.gl-titiler-cog-example build produces a working production bundle.

🤖 Generated with Claude Code

kylebarron and others added 9 commits April 24, 2026 14:01
Design for a new example that renders titiler .npy tiles via
RasterTileLayer directly (the first example using that layer without a
COGLayer/ZarrLayer subclass).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copies the cog-basic scaffolding (package.json, tsconfig, vite, index,
main) and adds a blank-map App. Adds npyjs and proj4 as deps.
- Extract titiler helpers (URLs, buildDescriptor, decode, getTileData,
  renderTile) into src/titiler.ts. App.tsx now only handles the React
  UI and layer wiring.
- Drop unused @developmentseed/proj dep; add peer dep @deck.gl/mesh-layers.
- Replace `parsed.data as Uint8Array` cast with an instanceof guard.
- Note texture-destroy semantics in getTileData docstring.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…n TMS

Two runtime fixes:

1. /cog/info returns bounds in the COG's native CRS (UTM for Sentinel-2),
   which MapLibre's fitBounds rejects with "Invalid LngLat latitude value".
   Switch to /cog/tilejson.json, whose bounds are in WGS84 per the TileJSON
   spec. Also thread the tilejson's minzoom/maxzoom onto the layer so we
   don't request tiles past the COG's resolution.

2. Titiler's /tileMatrixSets/WebMercatorQuad response omits the optional
   boundingBox field, which TileMatrixSetAdaptor requires for viewport
   culling. Inject one built from the tilejson's geographic bounds
   projected to EPSG:3857.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Titiler's route is /cog/{tileMatrixSetId}/tilejson.json, not
/cog/tilejson.json?tileMatrixSetId=...; the latter 404s.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@kylebarron kylebarron changed the title Titiler .npy tile example with RasterTileLayer feat: Titiler .npy tile example with RasterTileLayer Apr 24, 2026
@github-actions github-actions Bot added the feat label Apr 24, 2026
@vincentsarago

Copy link
Copy Markdown
Member

@kylebarron do you think developmentseed/titiler#1242 could be of any help, like having the number of bands or the datatype ...

- `GET /cog/tiles/WebMercatorQuad/{z}/{x}/{y}.npy?url=<COG_URL>` — returns
a numpy `.npy` file for one tile, shape `(bands, height, width)`,
dtype `uint8` for an RGB COG. For a 3-band RGB source titiler returns
4 bands: R, G, B, mask.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where does this limitation comes from? Titiler could server tiles with nBands+masks

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This limitation isn't "required"; it was just a simplifying assumption to get some sort of titiler example working.

NPZ would be fine; we'd just have to unzip the files


- `GET /cog/info?url=<COG_URL>` — returns metadata including
`bounds: [west, south, east, north]` in WGS84. Used to fit the map.
- `GET /tileMatrixSets/WebMercatorQuad` — returns an OGC TMS 2.0 JSON

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, we should keep in mind the difference between a:

  • RasterTileLayer: our concept, which supports arbitrary tile grids
  • upstream TileLayer: an official deck.gl layer which only supports the Web Mercator tiling grid but is a bit more optimized.

If a user only wants to render in web mercator, they can use the upstream TileLayer directly (with our RasterLayer as the generated sub layer).

@vincentsarago are there specific times when rendering in non-web mercator would be faster? Like if we rendered from the specific UTM zone a Sentinel tile was generated, for example?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it will be faster to reduce the re-projection pipeline, so if you choose a close CRS to the dataset CRS it should be faster (in theory)

@kylebarron

Copy link
Copy Markdown
Member Author

@kylebarron do you think developmentseed/titiler#1242 could be of any help, like having the number of bands or the datatype ...

First, take this implementation with a grain of salt. We don't have to use the tilejson endpoint in this app if there's a different endpoint that makes more sense.

I'm not sure I love overloading the tilejson with that other metadata, but perhaps it's better than making two different requests

@vincentsarago

vincentsarago commented Apr 27, 2026 •

Copy link
Copy Markdown
Member

First, take this implementation with a grain of salt. We don't have to use the tilejson endpoint in this app if there's a different endpoint that makes more sense.

I'm not sure I love overloading the tilejson with that other metadata, but perhaps it's better than making two different requests

Yeah I'm not super fan as well but at the moment there is no solution, both /tiles/{tileMatrixSetId} and /tilejson.json do not send information about the data they are giving access to. Application that does client side rendering will have to know in advance how many bands they will have in each tile and what is the datatype (at minimum). If you you the /info endpoint you get this information but they you also need to call the one of the previous endpoint to get the TMS coverage (bounds, min/max zoom)

@kylebarron

Copy link
Copy Markdown
Member Author

kylebarron added a commit that referenced this pull request Oct 8, 2026
Port #469 onto current main as an experimental example. It renders
tiles from the public titiler.xyz instance with RasterTileLayer directly:
titiler serves each tile as a raw NumPy `.npy` array, which the browser
decodes with npyjs and uploads as an RGBA texture plus a mask texture.

Changes from #469:

- Move to `examples/experimental/titiler-cog`. It keeps the flat
  `/examples/titiler-cog/` URL, and is badged experimental and listed in
  the experimental section of the docs examples page.
- Use the shared example components (ControlPanel, DebugControls,
  DeckGlOverlay, LoadingWidget) and current dependency versions.
- Adapt to the `TilesetDescriptor` -> `RasterTilesetDescriptor` rename.
- Destroy tile textures in `onTileUnload`, following the ownership model
  from the destroy-tile-textures design.
- Don't pass titiler's `minzoom` as `minZoom`. RasterTileLayer renders
  nothing below `minZoom`, so the imagery vanished when zooming out past
  z8, though titiler serves coarser tiles fine.
- Add a `host=` query parameter to every titiler URL. titiler echoes the
  request `Origin` as `Access-Control-Allow-Origin`, but titiler.xyz's
  CDN caches responses without regard to `Origin`, so it can serve a page
  a response cached for another site (or for curl, with no CORS header at
  all) and the browser blocks it. The host, rather than the full origin,
  because the CDN rejects query strings containing `http://localhost`.
- Check npy Fortran order, since the RGBA repack assumes C order.
- Show titiler's tilejson `data_type` and band count in the panel.

Co-authored-by: Claude Opus 5.5 <[email protected]>
kylebarron added a commit that referenced this pull request Oct 21, 2026
…689)

> [!NOTE]
> This PR was written by Claude (Claude Code), not by @kylebarron.

`RasterTileset2D` selects the same tile many times on aligned grids such
as WebMercatorQuad.

## Problem

Both `crsBoundsToTileRange` implementations (`TileMatrixAdaptor` and
`AffineTilesetLevel`) floor the box's max edge, so a tile that only
touches the box's right or bottom edge counts as overlapping. The
traversal finds a tile's children by passing the tile's bounds to the
next level's `crsBoundsToTileRange`. In an aligned pyramid
(WebMercatorQuad, or COG overviews that exactly halve), each parent's
right and bottom edges lie on child tile edges, so most parents also
claim their neighbors' children:

```ts
const { levels } = new TileMatrixSetAdaptor(webMercatorQuad, projections);
const { topLeft, bottomRight } = levels[1]!.projectedTileCorners(0, 0);
levels[2]!.crsBoundsToTileRange(topLeft[0], bottomRight[1], bottomRight[0], topLeft[1]);
// main:    { minCol: 0, maxCol: 2, minRow: 0, maxRow: 2 }
// this PR: { minCol: 0, maxCol: 1, minRow: 0, maxRow: 1 }
```

In zoom 2 tile units, tile 1/0/0 covers `[0, 2] x [0, 2]`. `floor(2)` is
2, so main also takes column 2 and row 2, whose tiles only share an edge
with it:

```
      x=0   x=1   x=2   x=3
  y=0 +-----+-----+-----+
      |  A  |  B  |  C  |     tile 1/0/0 covers A, B, D and E
  y=1 +-----+-----+-----+
      |  D  |  E  |  F  |     main:    floor(0)..floor(2) = 0..2 per axis -> A to I
  y=2 +-----+-----+-----+     this PR: 0..1 per axis -> A, B, D and E
      |  G  |  H  |  I  |
  y=3 +-----+-----+-----+
```

`RasterTileNode.children` builds a new node for every tile in the range,
and each node is selected on its own, so `getTileIndices` returns a tile
once per parent that claimed it. The extra children get extra children
of their own, so it compounds down the pyramid. For a 512×512
`WebMercatorViewport` at lng/lat 0, where every level's tile edges meet:

| TileMatrixSet | zoom 3 | zoom 10 |
| --- | --- | --- |
| titiler's WebMercatorQuad | 48 indices for 9 tiles | 286 for 9 |
| OGC example WebMercatorQuad (rounded cellSizes) | 64 for 9 | 3844 for
9 |

That view is the worst case for flat maps. With titiler's TileMatrixSet,
ordinary flat views get about 2-10× as many indices as tiles (e.g. 110
for 20 over San Francisco at zoom 12). The OGC example's gets more (1215
for 20 there), and pitched views get far more. lonboard's `RasterLayer`
and #469's titiler example go through this path.

What the repeats cost with deck.gl 9.4.0's `Tileset2D`:

- **No duplicate requests or draws.** `getTileData` runs once per tile,
and `renderLayers` iterates the unique `tileset.tiles`.
- **Cache size.** `selectedTiles` keeps every repeat, and the default
cache cap is `5 * selectedTiles.length`: 1430 instead of 45 for the zoom
10 view above. `onViewportLoad` also receives the repeats.
- **Traversal time** per `getTileIndices` call (warm cache, 1024×768
unless noted). Pitch 60 is lonboard's default maximum for map views.

  | View | main | this PR |
  | --- | --- | --- |
  | lng/lat 0, zoom 10, 512×512, titiler's TMS | 1.93 ms | 0.08 ms |
  | same, OGC example TMS | 15.2 ms | 0.08 ms |
  | Berlin, zoom 16, flat | 0.14 ms | 0.09 ms |
| Berlin, zoom 18, pitch 60 | 54.5 ms (26952 indices for 76 tiles) |
0.19 ms |
  | lat 50, zoom 8, pitch 75, bearing 45 | 874 ms | 3.3 ms |

- **Overlapping tiles.** Where the selected zoom level changes, a parent
can recurse while its right or bottom neighbor is selected at the
coarser level. The parent's extra child lies inside that neighbor and is
selected too, so the same area is fetched and drawn at two resolutions.
For example, at lat 40, zoom 2, pitch 45 that's 38 extra tiles.

  ```
  z     |------ P (recurses) ------|------ Q (selected) ------|
  z+1   |---- a -----|---- b ------|---- c -----|---- d ------|
  ```

On main, P's children are a, b and c. Q is selected at z, but c is still
tested at z+1 as P's child, so it's selected too and drawn over part of
Q.

The other two callers of `crsBoundsToTileRange` see the same rule.
`createRootTiles` (the culled path for large root matrices) keeps roots
that only touch the viewport. `resolveSecondaryTiles` (`MultiCOGLayer`)
fetches up to 2×2 secondary tiles for a primary tile whose right or
bottom edge lies on a secondary tile edge: 256 secondary fetches for 121
primary tiles on a Sentinel-2-like 10 m / 20 m pair, where 121 suffice.

Separately, when levels don't line up (COG overviews of odd sizes, e.g.
1373 → 2745 px), a child tile can straddle two parents and really is a
child of both. The traversal selects it once through each, so even with
exact ranges a 10980 px COG returns 16 indices for 9 tiles.

For a 10980 px COG with 512 px tiles, in full-resolution pixels:

```
                0            2048         4096         6144         8192
2745 px level   |---- c0 ----|---- c1 ----|---- c2 ----|---- c3 ----|
1373 px level   |---------- P0 ----------|---------- P1 -----------|
                0                     4094.5                      8189
```

c1 is 2046.5 px inside P0 and 1.5 px inside P1. If P1 recurses and P0
doesn't, c1 is the only finer tile that covers P1's 1.5 px sliver, so
both parents' ranges have to keep it.

## Changes

- **`crsBoundsToTileRange` leaves out tiles that only touch the box.** A
new internal helper, `overlappingTileSpan`, returns `[floor(start + ε),
ceil(end - ε) - 1]` along one axis with ε = 1e-6 of a tile. Both
implementations use it and keep their existing clamping. The
`RasterTilesetLevel` docs now state the rule, and the two test doubles
that compute ranges follow it.
- **`getTileIndices` returns each `z/x/y` once**, keeping the first
node, for levels that don't line up.

Across about 75 views and tilesets checked during the investigation
(flat, pitched up to 75°, rotated, world copies, globe; both
WebMercatorQuads, UTM31 through proj4; power-of-two, odd-size, 1:1 and
rotated COG pyramids), the new selection had no repeats and was always a
subset of the old one. No sampled screen point lost coverage: every tile
it no longer selects lies under a coarser tile that is still selected.
The timings above come from that investigation, on code with the same
source logic as this PR.

## Tests

- New `tile-children.test.ts`:
- Child ranges for both WebMercatorQuads (tile 1/0/0, and a sample of
tiles at every zoom), a power-of-two COG pyramid, a 1:1 level pair (tile
size doubles as cellSize halves), and a 10980 px COG whose coarser
overviews don't line up. The last one checks that every child that
really overlaps its parent is kept.
- `getTileIndices` with both WebMercatorQuads in six views (flat at zoom
3 and 10, pitched and rotated, pitched across zoom levels, world copies,
globe): no tile is selected twice or together with one of its ancestors.
  - `getTileIndices` on the 10980 px COG selects each tile once.
- `create-root-tiles.test.ts`: roots that only touch the viewport are
left out (6 roots instead of 12 on a 1° grid).
- `secondary-tile-resolver.test.ts`: one 20 m tile for a 10 m tile whose
edges lie on its edges, with real `AffineTilesetLevel`s. The mock level
used to count a tile that touches the box's left or top edge as
overlapping, so the existing "spanning two secondary tiles" case only
touched the first tile. The mock now follows the rule, and that case
uses a secondary grid that the primary tile really straddles.

Every new test fails on `main`. With the four changed source files
reverted (keeping the new helper), the three files give `Tests 22 failed
| 7 passed (29)`, and the 7 that pass are existing tests. For example:

- tile 1/0/0: `expected { minCol: +0, maxCol: 2, …(2) } to deeply equal
{ minCol: +0, maxCol: 1, …(2) }`
- titiler, zoom 10: `expected [ '11/1024/1023', …(276) ] to deeply equal
[]`

The non-aligned COG test fails against the first commit alone (`expected
16 to be 9`) and passes with the second.

With `main` (fff98f1) merged in:

- `pnpm -r --filter="!docs" build` and `pnpm -r --filter="!docs"
typecheck` pass (27 of 29 projects, every example included).
- `pnpm --filter @developmentseed/deck.gl-raster test` (197/197),
`@developmentseed/deck.gl-geotiff` (71/71) and
`@developmentseed/deck.gl-zarr` (16/16) pass.
- `pnpm exec biome ci .` passes.

## Notes

- **Behavior changes.** `MultiCOGLayer` now fetches one secondary tile,
not up to 2×2, for a primary tile whose right or bottom edge lies on a
secondary tile edge. With linear filtering those edges now clamp to the
texture edge, as the left and top edges always did. I haven't checked
this visually. Root culling is also tighter.
- **Tolerance.** Float error at aligned edges measured at most 3.3e-9 of
a tile, and 1e-6 of a 4096 px tile is about 0.004 px. It doesn't absorb
TileMatrixSets that round their cellSizes to a few digits. In the OGC
CDB1GlobalGrid example (2^-14 listed as 6.10351562e-05), 2269 of 2879
parents per row at that level still claim a neighbor's column. The
second commit keeps the output unique there, but the extra traversal
remains. Deriving children with integer arithmetic when levels line up
would fix that; I'd leave it for a follow-up.
- **Repeats are dropped from the output rather than avoided.** Keeping
one `RasterTileNode` per `z/x/y` within a traversal would also stop
shared children in non-aligned pyramids from being traversed twice. I
went with the smaller change.

With one node per `z/x/y`, the shared c1 from the example above would be
built and visited once:

  ```
  this PR: a tree                    one node per z/x/y: a DAG

      P0          P1                     P0          P1
     /  \        /  \                   /  \        /  \
    c0   c1    c1   ...                c0   \      /   ...
         |      |                            \    /
        ...    ...   built and                 c1
                     visited twice             |
... built and visited once
  ```

- **Rotated or skewed affine grids** don't benefit from the range
change, because child ranges come from the bounding box of the parent's
bounding box. The second commit keeps their output unique, but they
still traverse extra nodes.
- **`overlappingTileSpan` stays internal.** `RasterTilesetLevel` is
public, so other implementations follow the rule documented on the
interface rather than calling the helper.
- **Fixture.** `tile-children.test.ts` reads the OGC WebMercatorQuad
example from the morecantile spec submodule, as #684's tests do. CI
checks out submodules, but a clone without them fails these tests. If it
should be inlined, it's probably worth doing for both PRs together.
- **#684.** Its `raster-tileset-2d-extent.test.ts` dedups
`getTileIndices` output because "the traversal can return the same tile
more than once". Whichever of the two PRs lands second can drop that and
assert there are no repeats.
- Not checked: rendering in a browser (memory use, blending of
overlapping tiles below opacity 1), and whether repeated secondary
fetches were deduplicated at the HTTP level.

Ref #523 (per-frame traversal cost, which these extra nodes inflate),
Ref #684

🤖 Written by [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kylebarron added a commit that referenced this pull request Oct 21, 2026
…tent` (#684)

> [!NOTE]
> This PR was written by Claude (Claude Code), not by @kylebarron.

`TileMatrixSetAdaptor` threw "Bounding Box inference not yet
implemented" for any TileMatrixSet without the optional `boundingBox`.
That includes every TileMatrixSet in morecantile's registry (e.g.
`WebMercatorQuad`) and titiler's `/tileMatrixSets/{id}` responses, which
is how lonboard hit it when rendering titiler `.npy` tiles.

## Changes

- **Infer `projectedBounds` when `boundingBox` is missing**, from the
coarsest tile matrix, the same way morecantile's `TileMatrixSet.xy_bbox`
does. It uses `xy_bounds`, like the per-tile corners, so it handles
`cornerOfOrigin: "bottomLeft"` and follows the same axis conventions. An
explicit `boundingBox` still wins, since it can be tighter than the grid
(e.g. a TileMatrixSet generated for one COG).
- **Honor the `extent` prop in `RasterTileset2D`.** `RasterTileLayer`
already forwarded `extent` to its tileset, but
`RasterTileset2D.getTileIndices` overrides deck.gl's implementation and
never read it, so it was silently ignored. It's now intersected with the
descriptor's bounds on every call, so `setOptions` updates apply. This
matters once bounds can be inferred: for a global TileMatrixSet like
WebMercatorQuad they cover the whole world, and `extent` is how to load
only the dataset's area. `extent` is now documented on
`RasterTileLayerProps` as WGS84 `[minLng, minLat, maxLng, maxLat]`.
- **Add an internal `intersectBounds` helper** for that intersection.
`createRootTiles` used the same inline arithmetic to cull root tiles to
the viewport, so it uses the helper too.

With this, #469's `buildDescriptor` no longer needs to inject a
`boundingBox`; passing the dataset bounds as `extent` limits tile
loading instead.

## Tests

- New `tile-matrix-set-bounds.test.ts`: `WebMercatorQuad` without
`boundingBox` (the OGC example in the morecantile spec submodule), an
explicit `boundingBox`, and a 3×2 `bottomLeft` grid.
- New `raster-tileset-2d-extent.test.ts`: only tiles overlapping an
asymmetric extent are selected; an extent that misses the data selects
nothing; an extent changed through `setOptions` applies on the next
call.
- 5 of the 6 new tests fail against `main`. The explicit-`boundingBox`
test is a guard and passes either way.
- With `main` (350b898) merged in, `pnpm --filter
@developmentseed/deck.gl-raster test` (196/196), `pnpm --filter
@developmentseed/deck.gl-raster typecheck` and `biome ci .` pass.
- With the exact TileMatrixSet JSON lonboard sends (morecantile's
`WebMercatorQuad`, no `boundingBox`), v0.8.1 throws and this branch
returns ±20037508.342789244 on both axes.

## Notes

- Unlike deck.gl's default tileset, `extent` doesn't keep tiles loading
below `minZoom` here. The TSDoc says so.
- Not changed here: `MosaicTileset2D` in deck.gl-geotiff also overrides
`getTileIndices` without reading `extent`, although `MosaicLayer`
forwards it.

🤖 Written by [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Create example reading from titiler backend

2 participants