https://github.com/tversteeg/distance-field
:capital_abcd: Generate distance field bitmaps--vector compression for games
https://github.com/tversteeg/distance-field
graphics rust signed-distance-field
Last synced: about 1 year ago
JSON representation
:capital_abcd: Generate distance field bitmaps--vector compression for games
- Host: GitHub
- URL: https://github.com/tversteeg/distance-field
- Owner: tversteeg
- License: gpl-3.0
- Created: 2016-06-03T12:58:44.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2025-03-19T11:08:41.000Z (over 1 year ago)
- Last Synced: 2025-04-02T10:14:30.018Z (over 1 year ago)
- Topics: graphics, rust, signed-distance-field
- Language: Rust
- Homepage: https://docs.rs/distance-field
- Size: 575 KB
- Stars: 27
- Watchers: 2
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# distance-field
[](https://github.com/tversteeg/distance-field/actions?workflow=CI)
[](https://crates.io/crates/distance-field)
[](https://docs.rs/distance-field)
[](#license)
[](#downloads)
### [Documentation](https://docs.rs/distance-field/)
Generate distance field bitmaps for rendering as pseudo-vector images in shaders.
An example usecase for the library would be to automatically convert asset images. You can achieve this by having a `build.rs` similar to this:
```rust
use std::fs::File;
use distance_field::DistanceFieldExt;
fn convert_image_to_dfield(input: &str, output: &str) {
// Load the 'input' image
let img = image::open(input).unwrap();
// Generate a distance field from the image
let outbuf = img.grayscale().distance_field(distance_field::Options {
size: (128, 128),
max_distance: 256,
..Default::default()
});
// Save it to 'output' as a PNG
image::DynamicImage::ImageLuma8(outbuf).save(output).unwrap();
}
fn main() {
convert_image_to_dfield("img/input.png", "output.png");
}
```
# Generator binary
Checkout the repository and `cd` into it; then run:
cargo run --example generator -- img/input.png output.png 64 64
This will take the following image as input:

And generate a 64x64 distance field:

Now we can use the generated distance field to create a vector image.
### Using the distance field
First we need to scale it up with a linear interpolation:

Then we apply a treshold function:

You can see that we have something which looks very similar to the original input image and that just from a 64x64 image! But it's still very pixelated and doesn't look like a vector image. This can be fixed by not doing a hard treshold but allowing some shades of gray.