forked from stefanha/chunkymonkey
-
Notifications
You must be signed in to change notification settings - Fork 16
/
shard.go
334 lines (271 loc) · 8.59 KB
/
shard.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package shardserver
import (
"fmt"
"log"
"time"
"github.com/huin/chunkymonkey/chunkstore"
"github.com/huin/chunkymonkey/entity"
"github.com/huin/chunkymonkey/gamerules"
. "github.com/huin/chunkymonkey/types"
)
const chunksPerShard = ShardSize * ShardSize
// TODO Allow configuration of this.
const ticksBetweenSaves = TicksPerSecond * 60
// chunkXzToChunkIndex assumes that locDelta is offset relative to the shard
// origin.
func chunkXzToChunkIndex(locDelta *ChunkXz) int {
return int(locDelta.X)*ShardSize + int(locDelta.Z)
}
// ChunkShard represents a square shard of chunks that share a master
// goroutine.
type ChunkShard struct {
shardConnecter gamerules.IShardConnecter
chunkStore chunkstore.IChunkStore
entityMgr *entity.EntityManager
loc ShardXz
originChunkLoc ChunkXz // The lowest X and Z located chunk in the shard.
chunks [chunksPerShard]*Chunk
requests chan iShardRequest
ticksSinceUpdate Ticks
ticksSinceSave Ticks
saveChunks bool
newActiveBlocks []BlockXyz
newActiveShards map[uint64]*destActiveShard
shardClients map[uint64]gamerules.IShardShardClient
selfClient shardSelfClient
}
func NewChunkShard(shardConnecter gamerules.IShardConnecter, chunkStore chunkstore.IChunkStore, entityMgr *entity.EntityManager, loc ShardXz) (shard *ChunkShard) {
shard = &ChunkShard{
shardConnecter: shardConnecter,
chunkStore: chunkStore,
entityMgr: entityMgr,
loc: loc,
originChunkLoc: loc.ToChunkXz(),
requests: make(chan iShardRequest, 256),
ticksSinceUpdate: 0,
saveChunks: chunkStore.SupportsWrite(),
// Offset shard saves.
ticksSinceSave: (31 * Ticks(loc.Key())) % ticksBetweenSaves,
newActiveShards: make(map[uint64]*destActiveShard),
shardClients: make(map[uint64]gamerules.IShardShardClient),
}
shard.selfClient.shard = shard
return
}
// serve services shard requests in the foreground.
func (shard *ChunkShard) serve() {
ticker := time.NewTicker(NanosecondsInSecond / TicksPerSecond)
for {
select {
case <-ticker.C:
shard.tick()
case request := <-shard.requests:
request.perform(shard)
}
}
}
// tick runs the shard for a single tick.
func (shard *ChunkShard) tick() {
shard.ticksSinceUpdate++
for _, chunk := range shard.chunks {
if chunk != nil {
chunk.tick()
}
}
if shard.ticksSinceUpdate >= TicksPerSecond {
for _, chunk := range shard.chunks {
if chunk != nil {
chunk.sendUpdate()
}
}
shard.ticksSinceUpdate = 0
}
if shard.saveChunks && shard.chunkStore.SupportsWrite() {
shard.ticksSinceSave++
if shard.ticksSinceSave > ticksBetweenSaves {
log.Printf("%s: Writing chunks.", shard)
// TODO Stagger the per-chunk saves over multiple ticks.
for _, chunk := range shard.chunks {
if chunk != nil {
chunk.save(shard.chunkStore)
}
}
shard.ticksSinceSave = 0
}
}
shard.transferActiveBlocks()
}
// clientForShard is used to get a IShardShardClient for a given shard, reusing
// IShardShardClient connections for use within the shard. Returns nil if the
// shard does not exist.
func (shard *ChunkShard) clientForShard(shardLoc ShardXz) (client gamerules.IShardShardClient) {
var ok bool
if shard.loc.Equals(&shardLoc) {
return &shard.selfClient
}
shardKey := shardLoc.Key()
if client, ok = shard.shardClients[shardKey]; !ok {
client = shard.shardConnecter.ShardShardConnect(shardLoc)
if client != nil {
shard.shardClients[shardKey] = client
}
}
return
}
// blockQuery performs a relatively fast query of the BlockId at the given
// location. known=true if the returned blockTypeId is valid.
func (shard *ChunkShard) blockQuery(chunkLoc ChunkXz, subLoc *SubChunkXyz) (blockTypeId BlockId, known bool) {
chunkIndex, _, _, ok := shard.chunkIndexAndRelLoc(chunkLoc)
if !ok {
// blockLoc is in another shard.
// TODO Have a good fast case to deal with this.
return
}
chunk := shard.chunks[chunkIndex]
if chunk == nil {
// Chunk not loaded. Don't bother to load it just for a block query.
return
}
blockIndex, _ := subLoc.BlockIndex()
blockTypeId = chunk.blockId(blockIndex)
known = true
return
}
// transferActiveBlocks takes blocks marked as newly active by addActiveBlock,
// and informs the chunk in the destination shards.
func (shard *ChunkShard) transferActiveBlocks() {
if len(shard.newActiveBlocks) == 0 {
return
}
thisShardKey := shard.loc.Key()
for shardKey, activeShard := range shard.newActiveShards {
if shardKey == thisShardKey {
shard.reqSetBlocksActive(activeShard.blocks)
} else {
if client := shard.clientForShard(activeShard.loc); client != nil {
client.ReqSetActiveBlocks(activeShard.blocks)
}
}
}
}
// reqSetBlocksActive sets each block in the given slice to be active within
// the chunk. Note: if a block is within a different shard, it is discarded.
func (shard *ChunkShard) reqSetBlocksActive(blocks []BlockXyz) {
for _, block := range blocks {
chunkXz := block.ToChunkXz()
chunkIndex, _, _, isThisShard := shard.chunkIndexAndRelLoc(*chunkXz)
if isThisShard {
chunk := shard.chunks[chunkIndex]
if chunk == nil {
continue
}
chunk.AddActiveBlock(&block)
}
}
}
// addActiveBlock sets the given block to be active on the next tick. This
// works even if the block is not within the shard - it will be made active
// provided that the chunk that the block is within is loaded.
func (shard *ChunkShard) addActiveBlock(block *BlockXyz) {
chunkXz := block.ToChunkXz()
shardXz := chunkXz.ToShardXz()
shardKey := shardXz.Key()
activeShard, ok := shard.newActiveShards[shardKey]
if ok {
activeShard = &destActiveShard{
loc: shardXz,
blocks: []BlockXyz{*block},
}
shard.newActiveShards[shardKey] = activeShard
} else {
activeShard.blocks = append(activeShard.blocks, *block)
}
}
func (shard *ChunkShard) String() string {
return fmt.Sprintf("ChunkShard[%#v/%#v]", shard.loc, shard.originChunkLoc)
}
func (shard *ChunkShard) chunkIndexAndRelLoc(loc ChunkXz) (index int, x, z ChunkCoord, ok bool) {
x = loc.X - shard.originChunkLoc.X
z = loc.Z - shard.originChunkLoc.Z
if x < 0 || z < 0 || x >= ShardSize || z >= ShardSize {
return 0, 0, 0, false
}
ok = true
index = int(x*ShardSize + z)
return
}
// Get returns the Chunk at at given coordinates, loading it if it is not
// already loaded.
func (shard *ChunkShard) chunkAt(loc ChunkXz) *Chunk {
chunkIndex, dx, dz, ok := shard.chunkIndexAndRelLoc(loc)
if !ok {
log.Printf("%v.Get(%#v): ChunkXz outside of shard", shard, loc)
return nil
}
chunk := shard.chunks[chunkIndex]
// Chunk already loaded.
if chunk != nil {
return chunk
}
chunk = shard.loadChunk(loc, ChunkXz{dx, dz})
if chunk == nil {
// No chunk available at that location. (Return nil explicitly - interfaces
// containing nil pointer don't equal nil).
return nil
}
shard.chunks[chunkIndex] = chunk
return chunk
}
// loadChunk loads the specified chunk from store, and returns it.
// loc - The absolute world position of the chunk.
// locDelta - The relative position of the chunk within the shard.
func (shard *ChunkShard) loadChunk(loc ChunkXz, locDelta ChunkXz) *Chunk {
chunkResult := <-shard.chunkStore.ReadChunk(loc)
chunkReader, err := chunkResult.Reader, chunkResult.Err
if err != nil {
if _, ok := err.(chunkstore.NoSuchChunkError); !ok {
log.Printf("%v.load(%#v): chunk loading error: %v", shard, loc, err)
return nil
} else {
// Chunk doesn't exist in store.
return nil
}
}
chunk := newChunkFromReader(chunkReader, shard)
return chunk
}
// enqueueAllChunks runs a given function on all loaded chunks in the shard.
func (shard *ChunkShard) enqueueAllChunks(fn func(chunk *Chunk)) {
shard.requests <- &runOnAllChunks{fn}
}
// enqueueOnChunk runs a function on the chunk at the given location. If the
// chunk does not exist, it does nothing.
func (shard *ChunkShard) enqueueOnChunk(loc ChunkXz, fn func(chunk *Chunk)) {
shard.requests <- &runOnChunk{loc, fn}
}
func (shard *ChunkShard) enqueue(fn func()) {
shard.requests <- &runGeneric{fn}
}
func (shard *ChunkShard) enqueueRequest(req iShardRequest) {
shard.requests <- req
}
type destActiveShard struct {
loc ShardXz
blocks []BlockXyz
}
// shardSelfClient implements IShardShardClient for a shard to efficiently talk
// to itself.
type shardSelfClient struct {
shard *ChunkShard
}
func (client *shardSelfClient) Disconnect() {
}
func (client *shardSelfClient) ReqSetActiveBlocks(blocks []BlockXyz) {
client.shard.reqSetBlocksActive(blocks)
}
func (client *shardSelfClient) ReqTransferEntity(loc ChunkXz, entity gamerules.INonPlayerEntity) {
chunk := client.shard.chunkAt(loc)
if chunk != nil {
chunk.transferEntity(entity)
}
}