mapbox-martini

repository·main·Indexed 20 days ago

https://github.com/mapbox/martini

A JavaScript library for real-time terrain mesh generation using a quadtree-like approach. It provides efficient Level of Detail (LOD) by creating simplified meshes based on a specified error threshold via the Martini and Tile classes.

Tokens
665
Snippets
4
Records
4
Agent score
21%

What's inside martini

  1. Initialize Martini with a specific grid size

    main

    To use Martini, instantiate the Martini class. You must provide a gridSize that follows the pattern $2^n + 1$ (e.g., 257, 513, 1025). This size determines the resolution of the terrain tiles you will create.

    If the provided gridSize does not satisfy the $2^n + 1$ requirement, the constructor will throw an error.

    import Martini from 'martini';
    
    // Valid grid size (257 = 2^8 + 1)
    const martini = new Martini(257);
  2. Create a Tile from terrain data

    main

    Once a Martini instance is created, use createTile(terrain) to generate a Tile object.

    The terrain argument must be a flat array (e.g., Float32Array or Uint16Array) containing height values. The length of this array must exactly match gridSize * gridSize.

    const gridSize = 257;
    const terrain = new Float32Array(gridSize * gridSize);
    // ... fill terrain with height data ...
    
    const tile = martini.createTile(terrain);
  3. Generate a mesh from a Tile

    main

    Use the getMesh(maxError) method on a Tile instance to generate a simplified mesh based on an error threshold.

    • maxError: A numeric value representing the maximum allowed error. A higher maxError results in fewer triangles and a more simplified mesh. A maxError of 0 will attempt to represent the terrain as accurately as possible.

    Returns an object containing:

    • vertices: A Uint16Array of interleaved [x, y, x, y, ...] coordinates.
    • triangles: A Uint32Array of vertex indices forming triangles [a, b, c, a, b, c, ...].
    // Generate a mesh with a tolerance of 0.5
    const mesh = tile.getMesh(0.5);
    
    const { vertices, triangles } = mesh;
    // vertices contains [x0, y0, x1, y1, ...]
    // triangles contains [idx0, idx1, idx2, ...]
  4. Update Tile error calculations

    main

    The Tile.update() method recalculates the error map for the tile's terrain. This is necessary if the underlying terrain data has changed. It computes errors by comparing interpolated heights against actual terrain heights across the implicit binary tree structure used by Martini.

    // If terrain data is modified:
    // tile.terrain = newTerrain;
    
    tile.update();