dem2hm

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 8 Imported by: 3 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

dem2hm

dem2hm converts a digital elevation model (DEM) into a normalized integer heightmap designed for direct use by Go programs.

Usage

Run the application through Cargo from the repository root:

cargo run --release -- [OPTIONS] <INPUT> <OUTPUT>

After installing it with cargo install --path ., invoke the executable directly:

dem2hm [OPTIONS] <INPUT> <OUTPUT>

The input must be a single-image, single-band GeoTIFF with signed 8-, 16-, 32-, or 64-bit integer samples. If the GeoTIFF declares a GDAL_NODATA value, those pixels are encoded with the heightmap no-data sentinel and excluded when finding the normalization range.

Arguments:

  • <INPUT> is the source GeoTIFF DEM.
  • <OUTPUT> is the gzip-compressed heightmap file to create. Use the .hmz extension; its parent directory must already exist.

Options:

  • --rotate <0|90|180|270> rotates clockwise. The default is 0.
  • --flip-horizontal flips the rotated raster left-to-right.
  • --flip-vertical flips the rotated raster top-to-bottom.
  • -h, --help prints command-line help.
  • -V, --version prints the application version.

Rotation is applied first. Flips are then applied in output coordinates, so they always describe the final image's horizontal and vertical axes.

Panama DEM

From the repository root, this exact command reads ../dem/Pma_DEM_30m.tif, rotates it 90 degrees clockwise, flips the rotated image vertically, and writes ../var/pandemokh.hmz:

cargo run --release -- --rotate 90 --flip-vertical ../dem/Pma_DEM_30m.tif ../var/pandemokh.hmz

The ../var directory must exist before running the command.

The converter scans the TIFF once to find valid minimum and maximum elevations, then decodes and transforms one TIFF strip or tile at a time into a temporary payload. It finally streams that payload through gzip into the output file. It does not load the complete raster into memory.

Heightmap format, version 1 (frozen)

The version 1 wire format is frozen. Existing version 1 files will not be reinterpreted if the format evolves; an incompatible future format will use a new version and magic value.

The output is a raw 12-byte header followed immediately by one gzip member containing an int32 for every output pixel:

Byte offset Type Meaning
0 int32 Magic value 0x0108AAFF
4 int32 Height in rows
8 int32 Width in columns
12 gzip stream height * width normalized int32 pixels

Every integer in both the raw header and decompressed payload uses little-endian byte order. Thus, the first four bytes are FF AA 08 01. The gzip stream starts at byte 12 with bytes 1F 8B. Go can decode the payload with its standard compress/gzip package and decode the integers portably with encoding/binary.LittleEndian.

Pixel data is row-major, with each row written left-to-right from the top of the raster. Pixel (x, y) is stored at sample index:

y * width + x

Valid elevations are linearly normalized to 0..2147483647:

round((elevation - min) * 2147483647 / (max - min))

The reserved value -2147483648 marks a no-data pixel. The decompressed gzip payload has no padding or trailer, so its exact size is:

height * width * 4 bytes

The complete file size depends on the gzip compression ratio. The gzip header uses a zero modification time, making repeated conversions of identical input deterministic.

If every valid pixel has the same elevation, all valid pixels are written as 0 because the normalization span is zero.

Go module

This repository includes the Go module github.com/maloquacious/dem2hm, which provides the canonical heightmap reader so applications do not need to implement and test their own decoder. Read accepts an io.Reader, validates the complete version 1 stream, and returns pixels in a flat row-major []int32. Pixel provides bounds-checked access with an error, At is a fast path that panics on out-of-bounds coordinates, and Row returns a bounds-checked view into the heightmap's backing data.

Reading a heightmap in Go

heightmap, err := dem2hm.Read(r)
if err != nil {
	return err
}
elevation, err := heightmap.Pixel(x, y)

Malformed-input and bounds errors wrap exported constant errors, allowing callers to use errors.Is while retaining a detailed error message.

Malicious inputs

compress/gzip validates stream structure, CRC, and decompressed size, but it does not impose decompressed-size, compression-ratio, CPU-time, or elapsed-time limits. Read validates dimensions and reads exactly the declared payload, but its unrestricted API assumes the input is trusted because declared dimensions determine the final []int32 allocation.

Applications accepting untrusted files should call ReadWithOptions, set MaxPixels to an application-appropriate allocation ceiling, and pass the request or operation context:

heightmap, err := dem2hm.ReadWithOptions(r, dem2hm.Options{
	Context:   req.Context(),
	MaxPixels: 100_000_000,
})

The context is checked during header and compressed-stream reads. As with all APIs built on io.Reader, cancellation cannot interrupt a reader already blocked inside its Read method unless that source also supports cancellation, deadlines, or closure. HTTP handlers should use the request context, wrap the request body with http.MaxBytesReader to cap compressed input, and retain the server's normal timeout limits. Non-HTTP callers should apply an equivalent input-byte limit when the source is untrusted.

Input trust

The Rust converter is intended only for trusted TIFF inputs. It validates the TIFF structure and supported sample format, but it is not a sandbox and does not impose security-oriented file-size, memory, CPU, or elapsed-time limits. Do not expose the converter directly to untrusted uploads without enforcing those limits outside the process.

The intended upstream repository is https://github.com/maloquacious/dem2hm.

Authors

  • Michael D. Henderson
  • Amp

Documentation

Overview

Package dem2hm reads normalized heightmaps produced by the dem2hm converter.

Index

Examples

Constants

View Source
const (

	// NoDataPixel is the value reserved for a pixel with no elevation data.
	NoDataPixel int32 = -2147483648

	// ErrInvalidByteOrder indicates that the file does not start with the
	// version 1 magic value in little-endian byte order.
	ErrInvalidByteOrder = Error("invalid heightmap byte order or format")
	// ErrInvalidHeader indicates that the 12-byte heightmap header is incomplete.
	ErrInvalidHeader = Error("invalid heightmap header")
	// ErrInvalidDimensions indicates that the height or width is not positive,
	// or that the resulting payload size cannot be represented safely.
	ErrInvalidDimensions = Error("invalid heightmap dimensions")
	// ErrInvalidGzip indicates that the payload is not a valid gzip stream.
	ErrInvalidGzip = Error("invalid heightmap gzip stream")
	// ErrInvalidPayload indicates that the decompressed pixel payload does not
	// conform to the version 1 heightmap format.
	ErrInvalidPayload = Error("invalid heightmap payload")
	// ErrMultipleGzipMembers indicates that a second gzip member follows the
	// required payload member.
	ErrMultipleGzipMembers = Error("multiple gzip members")
	// ErrTrailingData indicates that data follows the single gzip member.
	ErrTrailingData = Error("trailing heightmap data")
	// ErrOutOfBounds indicates that a requested pixel or row is outside the map.
	ErrOutOfBounds = Error("heightmap coordinates out of bounds")
	// ErrLimitExceeded indicates that the heightmap exceeds a configured limit.
	ErrLimitExceeded = Error("heightmap resource limit exceeded")
	// ErrCanceled indicates that reading was canceled or its deadline expired.
	ErrCanceled = Error("heightmap read canceled")
)

Variables

This section is empty.

Functions

func Version

func Version() semver.Version

Types

type Error

type Error string

Error defines a constant error

func (Error) Error

func (e Error) Error() string

Error implements the Errors interface

type HeightMap

type HeightMap struct {
	Height int
	Width  int
	Data   []int32
}

HeightMap is a normalized raster stored in top-to-bottom row-major order.

func Read

func Read(r io.Reader) (*HeightMap, error)

Read reads a version 1 heightmap from r without an application-defined resource limit or cancellation context.

Example
package main

import (
	"bytes"
	_ "embed"
	"fmt"

	"github.com/maloquacious/dem2hm"
)

//go:embed testdata/example.hmz
var exampleHMZ []byte

func main() {
	heightmap, err := dem2hm.Read(bytes.NewReader(exampleHMZ))
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	emptyPixels := 0
	for _, pixel := range heightmap.Data {
		if pixel == dem2hm.NoDataPixel {
			emptyPixels++
		}
	}

	fmt.Println("height:", heightmap.Height)
	fmt.Println("width:", heightmap.Width)
	fmt.Println("empty pixels:", emptyPixels)

}
Output:
height: 2
width: 3
empty pixels: 2

func ReadWithOptions

func ReadWithOptions(r io.Reader, options Options) (*HeightMap, error)

ReadWithOptions reads a version 1 heightmap from r using options.

func (*HeightMap) At

func (hm *HeightMap) At(x, y int) int32

At returns the pixel at column x and row y. It panics if the coordinates are outside the heightmap.

func (*HeightMap) Pixel

func (hm *HeightMap) Pixel(x, y int) (int32, error)

Pixel returns the pixel at column x and row y.

func (*HeightMap) Row

func (hm *HeightMap) Row(y int) ([]int32, error)

Row returns row y as a view into the heightmap's backing data. Changes to the returned slice change the heightmap.

type Options

type Options struct {
	// Context is checked while reading and decoding. A nil Context is treated
	// as context.Background(). Cancellation cannot interrupt an underlying
	// io.Reader blocked in Read unless that reader also honors cancellation,
	// deadlines, or closure.
	Context context.Context
	// MaxPixels is the largest decoded heightmap to accept. Zero disables the
	// additional limit; format and address-space limits still apply.
	MaxPixels uint64
}

Options controls resource use while reading a heightmap.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL