# mbtiles-utils

Tile math for MBTiles tilesets in EPSG:3857 (Web Mercator). Provides 2D point/bounds classes, a `Tile` model, and a `MBTilesManager` for computing zoom levels and tile lists from geographic bounds.

---

## Classes

### `Point2D`

```typescript
new Point2D(x: number, y?: number)
new Point2D(source: Point2D)
new Point2D(array: [number, number])
new Point2D(obj: { x: number; y: number })
```

A 2D point in EPSG:3857 metres. Accepts four construction forms.

| Member | Description |
|--------|-------------|
| `x`, `y` | Coordinates |
| `toArray()` | Returns `[x, y]` |

---

### `Bounds2D`

```typescript
new Bounds2D(bounds: Bounds2DLike)
```

An axis-aligned bounding box. Throws `InvalidBoundsError` if `min.x > max.x` or `min.y > max.y`.

| Member | Description |
|--------|-------------|
| `min`, `max` | `Point2D` corners |
| `width` | `max.x - min.x` |
| `height` | `max.y - min.y` |
| `center` | Midpoint as `Point2D` |
| `project(from, to)` | Re-project corners in-place using proj4 |
| `toArray()` | Returns `[[minX, minY], [maxX, maxY]]` |
| `intersectBounds(b)` | Returns the intersection `Bounds2D`, or `null` if disjoint |

---

### `Tile`

```typescript
new Tile(z: number, x: number, y: number)
```

An MBTiles tile at zoom `z`, column `x`, row `y`.

| Member | Description |
|--------|-------------|
| `id` | String `"z/x/y"` |
| `z`, `x`, `y` | Tile coordinates |
| `bounds` | `Bounds2D` in EPSG:3857 metres |

---

### `MBTilesManager`

```typescript
const mgr = new MBTilesManager();
```

#### `computeZoom(bounds: Bounds2D): number`

Returns the zoom level at which the given bounds fit within a single tile. Result is a non-negative integer.

#### `computeTilelistFromBounds(bounds: Bounds2DLike, options?: { zoom?: number }): Tile[]`

Returns all `Tile` objects that cover `bounds` at the given (or computed) zoom level.

---

## Constants

| Constant | Value | Description |
|----------|-------|-------------|
| `MBTILES_CRS` | `"EPSG:3857"` | Coordinate reference system |
| `MBTILES_TILE_PIXEL_SIZE` | `256` | Pixels per tile side |
| `MBTILES_WORLD_BOUNDS` | `±20037508.34` | Full Web Mercator extent |

---

## Example

```typescript
import { Bounds2D, MBTilesManager } from "./mbtiles-utils";

const mgr = new MBTilesManager();

const bounds = new Bounds2D([
    [-500000, 6000000],
    [ 500000, 7000000],
]);

const zoom = mgr.computeZoom(bounds);         // e.g. 5
const tiles = mgr.computeTilelistFromBounds(bounds, { zoom });
// tiles is an array of Tile objects covering the area
```
