-
Notifications
You must be signed in to change notification settings - Fork 131
/
chunk.go
99 lines (86 loc) · 1.54 KB
/
chunk.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"log"
"math"
"sync"
"github.com/go-gl/mathgl/mgl32"
)
const (
ChunkWidth = 32
)
type Vec3 struct {
X, Y, Z int
}
func (v Vec3) Left() Vec3 {
return Vec3{v.X - 1, v.Y, v.Z}
}
func (v Vec3) Right() Vec3 {
return Vec3{v.X + 1, v.Y, v.Z}
}
func (v Vec3) Up() Vec3 {
return Vec3{v.X, v.Y + 1, v.Z}
}
func (v Vec3) Down() Vec3 {
return Vec3{v.X, v.Y - 1, v.Z}
}
func (v Vec3) Front() Vec3 {
return Vec3{v.X, v.Y, v.Z + 1}
}
func (v Vec3) Back() Vec3 {
return Vec3{v.X, v.Y, v.Z - 1}
}
func (v Vec3) Chunkid() Vec3 {
return Vec3{
int(math.Floor(float64(v.X) / ChunkWidth)),
0,
int(math.Floor(float64(v.Z) / ChunkWidth)),
}
}
func NearBlock(pos mgl32.Vec3) Vec3 {
return Vec3{
int(round(pos.X())),
int(round(pos.Y())),
int(round(pos.Z())),
}
}
type Chunk struct {
id Vec3
blocks sync.Map // map[Vec3]int
}
func NewChunk(id Vec3) *Chunk {
c := &Chunk{
id: id,
}
return c
}
func (c *Chunk) Id() Vec3 {
return c.id
}
func (c *Chunk) Block(id Vec3) int {
if id.Chunkid() != c.id {
log.Panicf("id %v chunk %v", id, c.id)
}
w, ok := c.blocks.Load(id)
if ok {
return w.(int)
}
return 0
}
func (c *Chunk) add(id Vec3, w int) {
if id.Chunkid() != c.id {
log.Panicf("id %v chunk %v", id, c.id)
}
c.blocks.Store(id, w)
}
func (c *Chunk) del(id Vec3) {
if id.Chunkid() != c.id {
log.Panicf("id %v chunk %v", id, c.id)
}
c.blocks.Delete(id)
}
func (c *Chunk) RangeBlocks(f func(id Vec3, w int)) {
c.blocks.Range(func(key, value interface{}) bool {
f(key.(Vec3), value.(int))
return true
})
}