gl01/internal/world/chunk.go

104 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-01-20 21:58:50 +08:00
package world
import (
"encoding/gob"
"io"
"log"
2022-02-24 20:20:33 +08:00
"edgaru089.ink/go/gl01/internal/util/itype"
2022-01-20 21:58:50 +08:00
)
const (
ChunkSizeX = 16
ChunkSizeY = 128
ChunkSizeZ = 16
)
type Chunk struct {
X, Z int // Chunk coordinate in global coordinate (y is always zero)
2022-10-12 08:24:00 +08:00
Id [ChunkSizeX][ChunkSizeY][ChunkSizeZ]uint16
Aux [ChunkSizeX][ChunkSizeY][ChunkSizeZ]int16
2022-01-20 21:58:50 +08:00
// render data kept unexported (therefore excluded from gob encoding)
renderChanged bool
vao, vbo uint32
vbolen int
2022-01-28 15:24:03 +08:00
water struct {
vao, vbo uint32
vbolen int
}
vertUpdate chan [2][]Vertex
2022-01-28 15:24:03 +08:00
world *World
2022-01-20 21:58:50 +08:00
}
func (c *Chunk) SetChunkID(x, z int) {
c.X = x
c.Z = z
c.renderChanged = true
}
2022-01-28 15:24:03 +08:00
func (c *Chunk) SetBlock(x, y, z int, id, aux int) {
2022-01-20 21:58:50 +08:00
c.Id[x][y][z] = uint16(id)
2022-10-12 08:24:00 +08:00
c.Aux[x][y][z] = int16(aux)
2022-01-20 21:58:50 +08:00
c.renderChanged = true
2022-02-24 20:20:33 +08:00
switch x {
case 0:
if cb, ok := c.world.Chunks[itype.Vec2i{c.X - 1, c.Z}]; ok {
cb.InvalidateRender()
}
case ChunkSizeX - 1:
if cb, ok := c.world.Chunks[itype.Vec2i{c.X + 1, c.Z}]; ok {
cb.InvalidateRender()
}
}
switch z {
case 0:
if cb, ok := c.world.Chunks[itype.Vec2i{c.X, c.Z - 1}]; ok {
cb.InvalidateRender()
}
case ChunkSizeZ - 1:
if cb, ok := c.world.Chunks[itype.Vec2i{c.X, c.Z + 1}]; ok {
cb.InvalidateRender()
}
}
2022-01-20 21:58:50 +08:00
}
// InvalidateRender should be called if a block inside the chunk has changed
// and the chunk needs to re-rendered.
func (c *Chunk) InvalidateRender() {
c.renderChanged = true
}
// LoadFromGob loads the chunk from a gob-encoded file.
func (c *Chunk) LoadFromGob(file io.Reader) {
d := gob.NewDecoder(file)
err := d.Decode(c)
if err != nil {
log.Print("LoadFromGob Error: ", err)
}
}
// LoadFromGobIndexed loads the chunk from a gob-encoded file, with the
// chunk Index overwritten.
func (c *Chunk) LoadFromGobIndexed(file io.Reader, x, z int) {
d := gob.NewDecoder(file)
err := d.Decode(c)
if err != nil {
log.Printf("LoadFromGobIndexed(x=%d, z=%d) Error: %s", x, z, err)
}
c.X = x
c.Z = z
}
// WriteToGob writes the chunk to a gob-encoded file.
func (c *Chunk) WriteToGob(file io.Writer) {
e := gob.NewEncoder(file)
err := e.Encode(c)
if err != nil {
log.Printf("WriteToGob(x=%d, z=%d) Error: %s", c.X, c.Z, err)
}
}