2025-01-13 11:10:48 +01:00
|
|
|
package network
|
2024-10-31 01:06:39 +01:00
|
|
|
|
|
|
|
import (
|
2025-01-15 10:50:51 +01:00
|
|
|
"bufio"
|
|
|
|
"encoding/binary"
|
2025-01-19 21:23:47 +01:00
|
|
|
"fmt"
|
2025-01-15 10:50:51 +01:00
|
|
|
"io"
|
2024-10-31 01:06:39 +01:00
|
|
|
"log"
|
|
|
|
"net"
|
2025-01-22 20:14:58 +01:00
|
|
|
"sync"
|
2024-10-31 01:06:39 +01:00
|
|
|
"time"
|
|
|
|
|
2025-01-13 11:10:48 +01:00
|
|
|
"gitea.boner.be/bdnugget/goonscape/types"
|
2024-10-31 01:06:39 +01:00
|
|
|
pb "gitea.boner.be/bdnugget/goonserver/actions"
|
2025-01-19 21:52:56 +01:00
|
|
|
rl "github.com/gen2brain/raylib-go/raylib"
|
2024-10-31 01:06:39 +01:00
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
)
|
|
|
|
|
2025-01-19 21:52:56 +01:00
|
|
|
const protoVersion = 1
|
|
|
|
|
2025-01-18 14:23:48 +01:00
|
|
|
var serverAddr = "boner.be:6969"
|
|
|
|
|
|
|
|
func SetServerAddr(addr string) {
|
|
|
|
serverAddr = addr
|
|
|
|
}
|
|
|
|
|
2025-01-19 21:23:47 +01:00
|
|
|
func ConnectToServer(username, password string, isRegistering bool) (net.Conn, int32, error) {
|
2025-01-18 14:23:48 +01:00
|
|
|
conn, err := net.Dial("tcp", serverAddr)
|
2024-10-31 01:06:39 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to dial server: %v", err)
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
2025-01-19 21:23:47 +01:00
|
|
|
log.Println("Connected to server. Authenticating...")
|
|
|
|
|
|
|
|
// Send auth message
|
|
|
|
authAction := &pb.Action{
|
|
|
|
Type: pb.Action_LOGIN,
|
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
}
|
|
|
|
if isRegistering {
|
|
|
|
authAction.Type = pb.Action_REGISTER
|
|
|
|
}
|
|
|
|
|
|
|
|
authBatch := &pb.ActionBatch{
|
2025-01-19 21:52:56 +01:00
|
|
|
Actions: []*pb.Action{authAction},
|
|
|
|
ProtocolVersion: protoVersion,
|
2025-01-19 21:23:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := writeMessage(conn, authBatch); err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf("failed to send auth: %v", err)
|
|
|
|
}
|
2025-01-15 10:58:11 +01:00
|
|
|
|
2025-01-19 21:23:47 +01:00
|
|
|
// Read server response
|
|
|
|
reader := bufio.NewReader(conn)
|
2025-01-15 10:58:11 +01:00
|
|
|
lengthBuf := make([]byte, 4)
|
|
|
|
if _, err := io.ReadFull(reader, lengthBuf); err != nil {
|
2025-01-19 21:23:47 +01:00
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf("failed to read auth response: %v", err)
|
2025-01-15 10:58:11 +01:00
|
|
|
}
|
|
|
|
messageLength := binary.BigEndian.Uint32(lengthBuf)
|
|
|
|
|
|
|
|
messageBuf := make([]byte, messageLength)
|
|
|
|
if _, err := io.ReadFull(reader, messageBuf); err != nil {
|
2025-01-19 21:23:47 +01:00
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf("failed to read auth response body: %v", err)
|
2024-10-31 01:06:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var response pb.ServerMessage
|
2025-01-15 10:58:11 +01:00
|
|
|
if err := proto.Unmarshal(messageBuf, &response); err != nil {
|
2025-01-19 21:23:47 +01:00
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf("failed to unmarshal auth response: %v", err)
|
|
|
|
}
|
|
|
|
|
2025-01-19 21:52:56 +01:00
|
|
|
if response.ProtocolVersion > protoVersion {
|
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf("server requires newer protocol version (server: %d, client: %d)",
|
|
|
|
response.ProtocolVersion, protoVersion)
|
|
|
|
}
|
|
|
|
|
2025-01-19 21:23:47 +01:00
|
|
|
if !response.AuthSuccess {
|
|
|
|
conn.Close()
|
|
|
|
return nil, 0, fmt.Errorf(response.ErrorMessage)
|
2024-10-31 01:06:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
playerID := response.GetPlayerId()
|
2025-01-19 21:23:47 +01:00
|
|
|
log.Printf("Successfully authenticated with player ID: %d", playerID)
|
2024-10-31 01:06:39 +01:00
|
|
|
return conn, playerID, nil
|
|
|
|
}
|
|
|
|
|
2025-01-18 22:27:22 +01:00
|
|
|
func HandleServerCommunication(conn net.Conn, playerID int32, player *types.Player, otherPlayers map[int32]*types.Player, quitChan <-chan struct{}) {
|
2025-01-15 10:50:51 +01:00
|
|
|
reader := bufio.NewReader(conn)
|
2025-01-22 20:14:58 +01:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
log.Printf("Recovered from panic in HandleServerCommunication: %v", r)
|
|
|
|
}
|
|
|
|
conn.Close()
|
|
|
|
if player.QuitDone != nil {
|
|
|
|
close(player.QuitDone)
|
|
|
|
}
|
|
|
|
}()
|
2025-01-13 10:00:23 +01:00
|
|
|
|
2025-01-13 11:10:48 +01:00
|
|
|
actionTicker := time.NewTicker(types.ClientTickRate)
|
2025-01-13 10:00:23 +01:00
|
|
|
defer actionTicker.Stop()
|
2025-01-18 23:23:03 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
// Create error channel for goroutine communication
|
|
|
|
errChan := make(chan error, 1)
|
2025-01-18 23:23:03 +01:00
|
|
|
done := make(chan struct{})
|
2025-01-13 00:31:15 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
// Start message sending goroutine
|
2024-10-31 01:06:39 +01:00
|
|
|
go func() {
|
2025-01-22 20:14:58 +01:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
log.Printf("Recovered from panic in message sender: %v", r)
|
|
|
|
errChan <- fmt.Errorf("message sender panic: %v", r)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2025-01-18 22:27:22 +01:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-quitChan:
|
2025-01-18 23:23:03 +01:00
|
|
|
// Send disconnect message to server
|
|
|
|
disconnectMsg := &pb.ActionBatch{
|
|
|
|
PlayerId: playerID,
|
|
|
|
Actions: []*pb.Action{{
|
|
|
|
Type: pb.Action_DISCONNECT,
|
|
|
|
PlayerId: playerID,
|
|
|
|
}},
|
|
|
|
}
|
|
|
|
writeMessage(conn, disconnectMsg)
|
|
|
|
done <- struct{}{}
|
2025-01-18 22:27:22 +01:00
|
|
|
return
|
2025-01-22 20:14:58 +01:00
|
|
|
case <-done:
|
|
|
|
return
|
2025-01-18 22:27:22 +01:00
|
|
|
case <-actionTicker.C:
|
|
|
|
player.Lock()
|
|
|
|
if len(player.ActionQueue) > 0 {
|
|
|
|
actions := make([]*pb.Action, len(player.ActionQueue))
|
|
|
|
copy(actions, player.ActionQueue)
|
|
|
|
batch := &pb.ActionBatch{
|
|
|
|
PlayerId: playerID,
|
|
|
|
Actions: actions,
|
|
|
|
Tick: player.CurrentTick,
|
|
|
|
}
|
|
|
|
player.ActionQueue = player.ActionQueue[:0]
|
|
|
|
player.Unlock()
|
|
|
|
|
|
|
|
if err := writeMessage(conn, batch); err != nil {
|
2025-01-22 20:14:58 +01:00
|
|
|
errChan <- err
|
2025-01-18 22:27:22 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
player.Unlock()
|
2024-10-31 01:06:39 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
// Main message receiving loop
|
|
|
|
go func() {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
log.Printf("Recovered from panic in message receiver: %v", r)
|
|
|
|
errChan <- fmt.Errorf("message receiver panic: %v", r)
|
|
|
|
}
|
|
|
|
}()
|
2025-01-19 00:51:49 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
for {
|
2025-01-19 00:51:49 +01:00
|
|
|
select {
|
2025-01-22 20:14:58 +01:00
|
|
|
case <-quitChan:
|
2025-01-18 22:27:22 +01:00
|
|
|
return
|
2025-01-22 20:14:58 +01:00
|
|
|
default:
|
|
|
|
lengthBuf := make([]byte, 4)
|
|
|
|
if _, err := io.ReadFull(reader, lengthBuf); err != nil {
|
|
|
|
if err != io.EOF {
|
|
|
|
errChan <- fmt.Errorf("failed to read message length: %v", err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
messageLength := binary.BigEndian.Uint32(lengthBuf)
|
2025-01-15 10:50:51 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
messageBuf := make([]byte, messageLength)
|
|
|
|
if _, err := io.ReadFull(reader, messageBuf); err != nil {
|
|
|
|
log.Printf("Failed to read message body: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2024-10-31 01:06:39 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
var serverMessage pb.ServerMessage
|
|
|
|
if err := proto.Unmarshal(messageBuf, &serverMessage); err != nil {
|
|
|
|
log.Printf("Failed to unmarshal server message: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
2024-10-31 01:06:39 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
player.Lock()
|
|
|
|
player.CurrentTick = serverMessage.CurrentTick
|
|
|
|
|
|
|
|
tickDiff := serverMessage.CurrentTick - player.CurrentTick
|
|
|
|
if tickDiff > types.MaxTickDesync {
|
|
|
|
for _, state := range serverMessage.Players {
|
|
|
|
if state.PlayerId == playerID {
|
|
|
|
player.ForceResync(state)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
player.Unlock()
|
2025-01-18 22:27:22 +01:00
|
|
|
|
|
|
|
for _, state := range serverMessage.Players {
|
|
|
|
if state.PlayerId == playerID {
|
2025-01-22 20:14:58 +01:00
|
|
|
player.Lock()
|
|
|
|
// Update initial position if not set
|
|
|
|
if player.PosActual.X == 0 && player.PosActual.Z == 0 {
|
|
|
|
player.PosActual = rl.Vector3{
|
|
|
|
X: float32(state.X * types.TileSize),
|
|
|
|
Y: 0,
|
|
|
|
Z: float32(state.Y * types.TileSize),
|
|
|
|
}
|
|
|
|
player.PosTile = types.Tile{X: int(state.X), Y: int(state.Y)}
|
2025-01-19 21:52:56 +01:00
|
|
|
}
|
2025-01-22 20:14:58 +01:00
|
|
|
player.Unlock()
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if otherPlayer, exists := otherPlayers[state.PlayerId]; exists {
|
|
|
|
otherPlayer.UpdatePosition(state, types.ServerTickRate)
|
|
|
|
} else {
|
|
|
|
otherPlayers[state.PlayerId] = types.NewPlayer(state)
|
2025-01-19 21:52:56 +01:00
|
|
|
}
|
2025-01-13 10:00:23 +01:00
|
|
|
}
|
2025-01-13 00:31:15 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
// Remove players that are no longer in the server state
|
|
|
|
for id := range otherPlayers {
|
|
|
|
if id != playerID {
|
|
|
|
delete(otherPlayers, id)
|
|
|
|
}
|
2025-01-18 22:27:22 +01:00
|
|
|
}
|
2025-01-13 10:00:23 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
if handler, ok := player.UserData.(types.ChatMessageHandler); ok && len(serverMessage.ChatMessages) > 0 {
|
|
|
|
handler.HandleServerMessages(serverMessage.ChatMessages)
|
2025-01-20 00:03:50 +01:00
|
|
|
}
|
|
|
|
}
|
2025-01-22 20:14:58 +01:00
|
|
|
}
|
|
|
|
}()
|
2025-01-20 00:03:50 +01:00
|
|
|
|
2025-01-22 20:14:58 +01:00
|
|
|
// Wait for error or quit signal
|
|
|
|
select {
|
|
|
|
case <-quitChan:
|
|
|
|
// Send disconnect message
|
|
|
|
disconnectMsg := &pb.ActionBatch{
|
|
|
|
PlayerId: playerID,
|
|
|
|
Actions: []*pb.Action{{
|
|
|
|
Type: pb.Action_DISCONNECT,
|
|
|
|
PlayerId: playerID,
|
|
|
|
}},
|
2024-10-31 01:06:39 +01:00
|
|
|
}
|
2025-01-22 20:14:58 +01:00
|
|
|
writeMessage(conn, disconnectMsg)
|
|
|
|
case err := <-errChan:
|
|
|
|
log.Printf("Network error: %v", err)
|
2024-10-31 01:06:39 +01:00
|
|
|
}
|
|
|
|
}
|
2025-01-15 10:50:51 +01:00
|
|
|
|
|
|
|
// Helper function to write length-prefixed messages
|
|
|
|
func writeMessage(conn net.Conn, msg proto.Message) error {
|
|
|
|
data, err := proto.Marshal(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write length prefix
|
|
|
|
lengthBuf := make([]byte, 4)
|
|
|
|
binary.BigEndian.PutUint32(lengthBuf, uint32(len(data)))
|
|
|
|
if _, err := conn.Write(lengthBuf); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write message body
|
|
|
|
_, err = conn.Write(data)
|
|
|
|
return err
|
|
|
|
}
|
2025-01-22 20:14:58 +01:00
|
|
|
|
|
|
|
type Connection struct {
|
|
|
|
conn net.Conn
|
|
|
|
playerID int32
|
|
|
|
quitChan chan struct{}
|
|
|
|
quitDone chan struct{}
|
|
|
|
closeOnce sync.Once
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConnection(username, password string, isRegistering bool) (*Connection, error) {
|
|
|
|
conn, playerID, err := ConnectToServer(username, password, isRegistering)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Connection{
|
|
|
|
conn: conn,
|
|
|
|
playerID: playerID,
|
|
|
|
quitChan: make(chan struct{}),
|
|
|
|
quitDone: make(chan struct{}),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Connection) Close() {
|
|
|
|
c.closeOnce.Do(func() {
|
|
|
|
close(c.quitChan)
|
|
|
|
// Wait with timeout for network cleanup
|
|
|
|
select {
|
|
|
|
case <-c.quitDone:
|
|
|
|
// Clean shutdown completed
|
|
|
|
case <-time.After(500 * time.Millisecond):
|
|
|
|
log.Println("Network cleanup timed out")
|
|
|
|
}
|
|
|
|
c.conn.Close()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Connection) PlayerID() int32 {
|
|
|
|
return c.playerID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Connection) Start(player *types.Player, otherPlayers map[int32]*types.Player) {
|
|
|
|
go HandleServerCommunication(c.conn, c.playerID, player, otherPlayers, c.quitChan)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Connection) QuitChan() <-chan struct{} {
|
|
|
|
return c.quitChan
|
|
|
|
}
|