Skip to content

Instantly share code, notes, and snippets.

@s-l-teichmann
Created October 22, 2012 04:03
Show Gist options
  • Save s-l-teichmann/3929576 to your computer and use it in GitHub Desktop.
Save s-l-teichmann/3929576 to your computer and use it in GitHub Desktop.
Example using 2D Simplex noise
// Copyright 2012 by Sascha L. Teichmann. All rights reserved.
//
// Simple example how to use 2D Simplex noise.
// $ go get bitbucket.org/s_l_teichmann/simplexnoise
// $ go build tilegen.go
//
package main
import (
"bitbucket.org/s_l_teichmann/simplexnoise"
"flag"
"fmt"
"image"
"image/color"
"image/png"
"log"
"os"
)
// Simplex noise returns [-1, 1] so we scale it to [0, 255].
func to_gray(v float64) color.Gray {
return color.Gray{uint8((v + 1.0) * 128.0)}
}
func main() {
var (
seed int64
size int
xofs int
yofs int
step float64
output string
)
flag.Int64Var(&seed, "seed", 1, "random seed")
flag.IntVar(&size, "size", 64, "tile size")
flag.IntVar(&xofs, "xofs", 0, "xofs")
flag.IntVar(&yofs, "yofs", 0, "yofs")
flag.Float64Var(&step, "step", 1.0/256.0, "step")
flag.StringVar(&output, "output", "", "file to store the tile")
flag.Parse()
img := image.NewGray(image.Rect(0, 0, size, size))
sn := simplexnoise.NewSimplexNoise(seed)
y_pos := float64(yofs*size) * step
x_start := float64(xofs*size) * step
for y := 0; y < size; y++ {
x_pos := x_start
for x := 0; x < size; x++ {
img.Set(x, y, to_gray(sn.Noise2D(x_pos, y_pos)))
x_pos += step
}
y_pos += step
}
if output == "" {
output = fmt.Sprintf("%d-%d.png", xofs, yofs)
}
file, err := os.Create(output)
if err != nil {
log.Printf("Cannot open '%s'", output)
os.Exit(1)
}
defer file.Close()
if err := png.Encode(file, img); err != nil {
log.Printf("Encoding failed '%s'", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment