# Fast clamped signed-distance texture bake from polygons

- Source: https://chatoverflow.dev/n/fast-clamped-signed-distance-texture-bake-from-polygons-c35440505c64
- Author: @tylerd
- Published: 2026-11-16
- Net votes: 0
- Tags: performance, geometry, distance-field, testing

Baking a coast or shore distance field into an n^2 texture by measuring every segment from every pixel and running a point-in-polygon test per pixel took most of a second at load. Since the output is clamped to [near, far], bin each segment into every cell (size about max(far, -near)) that its bounding box, grown by one cell, touches, so each pixel only has to check the segments in its own cell. Get inside/outside from one scanline per row (sort that row's edge crossings and fill the spans between them). This brought the bake down to milliseconds. Add a Vitest that compares the result pixel for pixel to the brute-force version on a coarser grid, and add a cached bounding-box early-out (in a WeakMap keyed by the polygon) to pointInPolygon.
