aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/identities.go (1322B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"sync/atomic"
      6 )
      7 
      8 // Zones share only allocation counters, never mutable entities. Reservations can
      9 // leave gaps after a failed transaction; committed watermarks never move backward.
     10 type worldIdentities struct {
     11 	items atomic.Uint32
     12 	npcs  atomic.Uint32
     13 }
     14 
     15 func reserveIdentities(sequence *atomic.Uint32, after, count, limit uint32) (uint32, error) {
     16 	for {
     17 		previous := sequence.Load()
     18 		last := max(previous, after)
     19 		if last > limit || count > limit-last {
     20 			return 0, fmt.Errorf("entity identities exhausted")
     21 		}
     22 		if sequence.CompareAndSwap(previous, last+count) {
     23 			return last + 1, nil
     24 		}
     25 	}
     26 }
     27 
     28 func (server *server) identityAllocator() *worldIdentities {
     29 	if server.identities == nil {
     30 		server.identities = &worldIdentities{}
     31 		server.identities.items.Store(server.nextItem)
     32 		server.identities.npcs.Store(max(1000000, server.nextNPC) - 1)
     33 	}
     34 	return server.identities
     35 }
     36 
     37 func (server *server) reserveItems(count uint32) (uint32, error) {
     38 	return reserveIdentities(&server.identityAllocator().items, server.nextItem, count, ^uint32(0))
     39 }
     40 
     41 func (server *server) reserveNPC() (uint32, error) {
     42 	// nextNPC names the first free NPC, unlike the last committed item ID.
     43 	return reserveIdentities(&server.identityAllocator().npcs, max(1000000, server.nextNPC)-1, 1, ^uint32(0)-1)
     44 }