gl01/internal/world/worldgen/worldgen.go

93 lines
2.2 KiB
Go
Raw Normal View History

2022-01-20 21:58:50 +08:00
package worldgen
import (
"sync"
packworld "edgaru089.ml/go/gl01/internal/world"
2022-01-28 15:24:03 +08:00
"edgaru089.ml/go/gl01/internal/world/blocks"
2022-01-20 21:58:50 +08:00
"github.com/aquilax/go-perlin"
)
const (
Alpha = 5 // Weight forming the noise sum
Beta = 2 // harmonic scaling/spacing
N = 3 // iterations
AltitudeDensity = 10 // Density of the noise in altitude
Sealevel = 63 // Space with Y=63 and lower should be the sea
2022-01-28 15:24:03 +08:00
Highest = 84 // Highest part of the terrain
Lowest = 60 // Lowest part of the terrain
2022-01-20 21:58:50 +08:00
)
var perlins map[int64]*perlin.Perlin
var perlinsLock sync.RWMutex
func init() {
perlins = make(map[int64]*perlin.Perlin)
}
// Chunk generates the chunk (must with chunkID set!!) with seed.
func Chunk(chunk *packworld.Chunk, world *packworld.World, seed int64) {
perlinsLock.RLock()
p, ok := perlins[seed]
if !ok {
perlinsLock.RUnlock()
perlinsLock.Lock()
p = perlin.NewPerlin(Alpha, Beta, N, seed)
perlins[seed] = p
perlinsLock.Unlock()
} else {
perlinsLock.RUnlock()
}
//log.Printf("noise=%.5f", p.Noise2D(0.1, 0.1))
offX := packworld.ChunkSizeX * chunk.X
offZ := packworld.ChunkSizeZ * chunk.Z
for x := 0; x < packworld.ChunkSizeX; x++ {
for z := 0; z < packworld.ChunkSizeZ; z++ {
height := Lowest + int(float64(Highest-Lowest)*p.Noise2D(
float64(offX+x)/AltitudeDensity,
float64(offZ+z)/AltitudeDensity))
//log.Printf("height = %d (noise=%.5f)", height, p.Noise2D(float64(offX+x), float64(offZ+z)))
2022-01-28 15:24:03 +08:00
// water
for y := Sealevel; y > height; y-- {
chunk.Id[x][y][z] = blocks.Water
}
2022-01-20 21:58:50 +08:00
// covering dirt
2022-01-28 15:24:03 +08:00
if height >= Sealevel {
chunk.Id[x][height][z] = blocks.Grass
} else {
chunk.Id[x][height][z] = blocks.Dirt
}
//chunk.Id[x][height][z] = blocks.DebugDir
chunk.Id[x][height-1][z] = blocks.Dirt
chunk.Id[x][height-2][z] = blocks.Dirt
chunk.Id[x][height-3][z] = blocks.Dirt
2022-01-20 21:58:50 +08:00
height -= 4
// stone in the middle
for y := height; y >= 1; y-- {
2022-01-28 15:24:03 +08:00
chunk.Id[x][y][z] = blocks.Stone
2022-01-20 21:58:50 +08:00
}
// bedrock at the bottom
2022-01-28 15:24:03 +08:00
chunk.Id[x][0][z] = blocks.Bedrock
2022-01-20 21:58:50 +08:00
// plant trees
if height >= 50 && height <= 70 {
if p.Noise2D(float64(offX+x), float64(offZ+z)) > 0.9 {
}
}
}
}
chunk.InvalidateRender()
}