Here’s a minimal, from-scratch 3D terrain generator in Go with a movable camera—all in pure Go (no OpenGL, no SDL, no 3D libraries). It serves an HTML page so you can use your browser arrow/WASD keys to fly around the generated terrain, and the server will re-render a fresh PNG on each move.
Project Structure
terrain-gen/
├── go.mod
├── cmd/
│ └── server/
│ └── main.go
└── internal/
├── camera/
│ └── camera.go
├── math3d/
│ ├── matrix.go
│ └── vector.go
├── render/
│ └── render.go
└── terrain/
├── perlin.go
└── terrain.go
1. go.mod
module terrain-gen
go 1.20
2. cmd/server/main.go
This spins up an HTTP server with three endpoints:
/ serves a tiny HTML+JS page.
/move?dir=… adjusts the camera.
/image returns the latest rendered PNG.
package main
import (
"image/png"
"log"
"net/http"
"strconv"
"sync"
"terrain-gen/internal/camera"
"terrain-gen/internal/render"
"terrain-gen/internal/terrain"
)
var (
cam *camera.Camera
terr *terrain.Terrain
lastImg = render.NewRenderer()
imgMutex sync.Mutex
)
func main() {
// 1) Initialize terrain & camera
terr = terrain.NewTerrain(200, 200, 0.1)
cam = camera.NewCamera(terrain.Vector3{X: 100, Y: 50, Z: -200})
// 2) Pre-render once
regenerateImage()
// 3) HTTP handlers
http.HandleFunc("/", handleIndex)
http.HandleFunc("/move", handleMove)
http.HandleFunc("/image", handleImage)
log.Println("Server at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
html := `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Go Terrain</title></head>
<body>
<h3>Use WASD QE or Arrow Keys to move</h3>
<img id="view" src="/image" width="800" height="600">
<script>
document.onkeydown = e => {
let dir = "";
switch(e.key) {
case "ArrowUp": dir="forward"; break;
case "ArrowDown": dir="back"; break;
case "ArrowLeft": dir="left"; break;
case "ArrowRight": dir="right"; break;
case "w": dir="forward"; break;
case "s": dir="back"; break;
case "a": dir="left"; break;
case "d": dir="right"; break;
case "q": dir="down"; break;
case "e": dir="up"; break;
}
if(dir){
fetch("/move?dir="+dir).then(_=>{
const img = document.getElementById("view");
img.src="/image?ts="+Date.now();
});
}
};
</script>
</body>
</html>`
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(html))
}
func handleMove(w http.ResponseWriter, r *http.Request) {
dir := r.URL.Query().Get("dir")
const step = 5.0
switch dir {
case "forward":
cam.MoveForward(step)
case "back":
cam.MoveForward(-step)
case "left":
cam.MoveRight(-step)
case "right":
cam.MoveRight(step)
case "up":
cam.MoveUp(step)
case "down":
cam.MoveUp(-step)
}
regenerateImage()
w.WriteHeader(204)
}
func handleImage(w http.ResponseWriter, r *http.Request) {
imgMutex.Lock()
defer imgMutex.Unlock()
w.Header().Set("Content-Type", "image/png")
png.Encode(w, lastImg.Image())
}
func regenerateImage() {
imgMutex.Lock()
defer imgMutex.Unlock()
lastImg.Render(terr, cam)
}
3. internal/terrain/terrain.go
Generate a heightmap using Perlin noise, and expose a mesh of triangles.
package terrain
type Terrain struct {
Width, Height int
Scale float64
heights [][]float64
}
// NewTerrain builds a Width×Height grid of heights in [0,1].
func NewTerrain(w, h int, scale float64) *Terrain {
t := &Terrain{
Width: w,
Height: h,
Scale: scale,
heights: func() [][]float64 {
m := make([][]float64, h)
for i := range m {
m[i] = make([]float64, w)
}
return m
}(),
}
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
t.heights[y][x] = Perlin2D(float64(x)*scale, float64(y)*scale, 6)
}
}
return t
}
// HeightAt returns the height at grid point (x,y).
func (t *Terrain) HeightAt(x, y int) float64 {
return t.heights[y][x]
}
// MeshTriangles returns all triangles (as triplets of Vector3) of the terrain grid.
func (t *Terrain) MeshTriangles() [][3]Vector3 {
tris := make([][3]Vector3, 0, (t.Width-1)*(t.Height-1)*2)
for y := 0; y < t.Height-1; y++ {
for x := 0; x < t.Width-1; x++ {
// four corners
p00 := Vector3{X: float64(x), Y: t.heights[y][x] * 20, Z: float64(y)}
p10 := Vector3{X: float64(x + 1), Y: t.heights[y][x+1] * 20, Z: float64(y)}
p01 := Vector3{X: float64(x), Y: t.heights[y+1][x] * 20, Z: float64(y + 1)}
p11 := Vector3{X: float64(x + 1), Y: t.heights[y+1][x+1] * 20, Z: float64(y + 1)}
// two triangles per quad
tris = append(tris, [3]Vector3{p00, p10, p11})
tris = append(tris, [3]Vector3{p00, p11, p01})
}
}
return tris
}
Perlin Noise: internal/terrain/perlin.go
A simple 2D Perlin implementation.
package terrain
import (
"math"
"math/rand"
)
func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) }
func lerp(a, b, t float64) float64 { return a + t*(b-a) }
func grad(hash int, x, y float64) float64 {
h := hash & 3
u := []float64{x, y}[h&1]
v := []float64{y, x}[h>>1&1]
if h&1 == 0 {
u = -u
}
if h&2 == 0 {
v = -v
}
return u + v
}
var p [512]int
func init() {
// build permutation table
perm := rand.Perm(256)
for i := 0; i < 256; i++ {
p[i] = perm[i]
p[i+256] = perm[i]
}
}
// Perlin2D returns noise in [0,1]
func Perlin2D(x, y float64, octaves int) float64 {
total := 0.0
freq := 1.0
amp := 1.0
max := 0.0
for i := 0; i < octaves; i++ {
total += singlePerlin(x*freq, y*freq) * amp
max += amp
amp *= 0.5
freq *= 2
}
return math.Min(1, math.Max(0, (total/max+1)/2))
}
func singlePerlin(x, y float64) float64 {
xi := int(math.Floor(x)) & 255
yi := int(math.Floor(y)) & 255
xf := x - math.Floor(x)
yf := y - math.Floor(y)
u := fade(xf)
v := fade(yf)
aa := p[p[xi]+yi]
ab := p[p[xi]+yi+1]
ba := p[p[xi+1]+yi]
bb := p[p[xi+1]+yi+1]
x1 := lerp(grad(aa, xf, yf), grad(ba, xf-1, yf), u)
x2 := lerp(grad(ab, xf, yf-1), grad(bb, xf-1, yf-1), u)
return lerp(x1, x2, v)
}
4. internal/math3d/vector.go
3D vector with basic ops.
package math3d
import "math"
type Vector3 struct {
X, Y, Z float64
}
func (a Vector3) Add(b Vector3) Vector3 { return Vector3{a.X + b.X, a.Y + b.Y, a.Z + b.Z} }
func (a Vector3) Sub(b Vector3) Vector3 { return Vector3{a.X - b.X, a.Y - b.Y, a.Z - b.Z} }
func (a Vector3) Mul(s float64) Vector3 { return Vector3{a.X * s, a.Y * s, a.Z * s} }
func (a Vector3) Dot(b Vector3) float64 { return a.X*b.X + a.Y*b.Y + a.Z*b.Z }
func (a Vector3) Cross(b Vector3) Vector3 {
return Vector3{
X: a.Y*b.Z - a.Z*b.Y,
Y: a.Z*b.X - a.X*b.Z,
Z: a.X*b.Y - a.Y*b.X,
}
}
func (a Vector3) Len() float64 { return math.Sqrt(a.Dot(a)) }
func (a Vector3) Normalize() Vector3 {
l := a.Len()
if l == 0 {
return a
}
return a.Mul(1 / l)
}
5. internal/math3d/matrix.go
4×4 matrices for transforms.
package math3d
import "math"
type Matrix4 [4][4]float64
// Identity matrix
func Identity() Matrix4 {
return Matrix4{
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
}
}
// Multiply two 4×4
func (a Matrix4) Mul(b Matrix4) Matrix4 {
var out Matrix4
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
sum := 0.0
for k := 0; k < 4; k++ {
sum += a[i][k] * b[k][j]
}
out[i][j] = sum
}
}
return out
}
// Transform a Vector3 (assumes w=1)
func (m Matrix4) Transform(v Vector3) Vector3 {
x := v.X*m[0][0] + v.Y*m[1][0] + v.Z*m[2][0] + m[3][0]
y := v.X*m[0][1] + v.Y*m[1][1] + v.Z*m[2][1] + m[3][1]
z := v.X*m[0][2] + v.Y*m[1][2] + v.Z*m[2][2] + m[3][2]
w := v.X*m[0][3] + v.Y*m[1][3] + v.Z*m[2][3] + m[3][3]
if w != 0 && w != 1 {
return Vector3{x / w, y / w, z / w}
}
return Vector3{x, y, z}
}
// Perspective projection
func Perspective(fov, aspect, zn, zf float64) Matrix4 {
f := 1.0 / math.Tan(fov*0.5)
return Matrix4{
{f / aspect, 0, 0, 0},
{0, f, 0, 0},
{0, 0, zf / (zf - zn), 1},
{0, 0, -zn * zf / (zf - zn), 0},
}
}
// LookAt camera matrix
func LookAt(eye, center, up Vector3) Matrix4 {
f := center.Sub(eye).Normalize()
s := f.Cross(up.Normalize()).Normalize()
u := s.Cross(f)
m := Identity()
m[0][0], m[1][0], m[2][0] = s.X, s.Y, s.Z
m[0][1], m[1][1], m[2][1] = u.X, u.Y, u.Z
m[0][2], m[1][2], m[2][2] = -f.X, -f.Y, -f.Z
m[3][0], m[3][1], m[3][2] = -s.Dot(eye), -u.Dot(eye), f.Dot(eye)
return m
}
6. internal/camera/camera.go
Simple FPS-style camera.
package camera
import (
"math"
"terrain-gen/internal/math3d"
)
type Camera struct {
Pos math3d.Vector3
Yaw float64
Pitch float64
}
// NewCamera sets up at position looking toward +Z.
func NewCamera(pos math3d.Vector3) *Camera {
return &Camera{Pos: pos, Yaw: 0, Pitch: 0}
}
func (c *Camera) Forward() math3d.Vector3 {
return math3d.Vector3{
X: math.Cos(c.Pitch) * math.Sin(c.Yaw),
Y: math.Sin(c.Pitch),
Z: math.Cos(c.Pitch) * math.Cos(c.Yaw),
}.Normalize()
}
func (c *Camera) Right() math3d.Vector3 {
return math3d.Vector3{
X: math.Sin(c.Yaw - math.Pi/2),
Y: 0,
Z: math.Cos(c.Yaw - math.Pi/2),
}.Normalize()
}
func (c *Camera) Up() math3d.Vector3 {
return c.Right().Cross(c.Forward()).Normalize()
}
// Movement
func (c *Camera) MoveForward(d float64) {
c.Pos = c.Pos.Add(c.Forward().Mul(d))
}
func (c *Camera) MoveRight(d float64) {
c.Pos = c.Pos.Add(c.Right().Mul(d))
}
func (c *Camera) MoveUp(d float64) {
c.Pos = c.Pos.Add(c.Up().Mul(d))
}
// You can add Rotate methods if you like…
7. internal/render/render.go
A very basic wireframe rasterizer into an image.RGBA.
package render
import (
"image"
"image/color"
"terrain-gen/internal/camera"
"terrain-gen/internal/math3d"
"terrain-gen/internal/terrain"
)
type Renderer struct {
img *image.RGBA
}
func NewRenderer() *Renderer {
w, h := 800, 600
return &Renderer{
img: image.NewRGBA(image.Rect(0, 0, w, h)),
}
}
// Image returns the last rendered frame
func (r *Renderer) Image() image.Image {
return r.img
}
// Render the entire terrain from cam's POV (wireframe)
func (r *Renderer) Render(t *terrain.Terrain, cam *camera.Camera) {
w := float64(r.img.Bounds().Dx())
h := float64(r.img.Bounds().Dy())
// 1) build MVP matrix
proj := math3d.Perspective(math3d.Deg2Rad(60), w/h, 0.1, 1000)
look := math3d.LookAt(cam.Pos, cam.Pos.Add(cam.Forward()), cam.Up())
mvp := proj.Mul(look)
// 2) clear
bg := color.RGBA{30, 30, 50, 255}
for y := 0; y < r.img.Bounds().Dy(); y++ {
for x := 0; x < r.img.Bounds().Dx(); x++ {
r.img.Set(x, y, bg)
}
}
// 3) draw each triangle as 3 lines
tris := t.MeshTriangles()
white := color.RGBA{200, 200, 200, 255}
for _, tri := range tris {
pts := [3]math3d.Vector3{
mvp.Transform(tri[0]),
mvp.Transform(tri[1]),
mvp.Transform(tri[2]),
}
// NDC to screen
screen := [3]image.Point{}
for i, p := range pts {
x := int((p.X*0.5+0.5)*w + 0.5)
y := int((1-(p.Y*0.5+0.5))*h + 0.5)
screen[i] = image.Pt(x, y)
}
r.line(screen[0].X, screen[0].Y, screen[1].X, screen[1].Y, white)
r.line(screen[1].X, screen[1].Y, screen[2].X, screen[2].Y, white)
r.line(screen[2].X, screen[2].Y, screen[0].X, screen[0].Y, white)
}
}
// Bresenham’s line
func (r *Renderer) line(x0, y0, x1, y1 int, col color.Color) {
dx := abs(x1 - x0)
sx := 1
if x0 > x1 {
sx = -1
}
dy := -abs(y1 - y0)
sy := 1
if y0 > y1 {
sy = -1
}
err := dx + dy
for {
if x0 >= 0 && y0 >= 0 && x0 < r.img.Bounds().Dx() && y0 < r.img.Bounds().Dy() {
r.img.Set(x0, y0, col)
}
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 >= dy {
err += dy
x0 += sx
}
if e2 <= dx {
err += dx
y0 += sy
}
}
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
Add this helper to convert degrees to radians:
// in internal/math3d/matrix.go
func Deg2Rad(deg float64) float64 {
return deg * math.Pi / 180
}
How to run
cd terrain-gen
go mod tidy
go run ./cmd/server
- Open your browser to http://localhost:8080 and use WASD/QE or arrow keys to fly around!
That’s it—pure Go, no external 3D or windowing libs, full terrain generator, wireframe rasterizer, and a movable camera you control in your browser. Have fun exploring your procedurally generated world! 🚀