/
packet.go
43 lines (38 loc) · 1.57 KB
/
packet.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
package packet
import (
"bytes"
"github.com/sandertv/gophertunnel/minecraft/protocol"
)
// Packet represents a packet that may be sent over a Minecraft network connection. The packet needs to hold
// a method to encode itself to binary and decode itself from binary.
type Packet interface {
// ID returns the ID of the packet. All of these identifiers of packets may be found in id.go.
ID() uint32
// Marshal encodes the packet to its binary representation into buf.
Marshal(buf *bytes.Buffer)
// Unmarshal decodes a serialised packet in buf into the Packet instance. The serialised packet passed
// into Unmarshal will not have a header in it.
Unmarshal(buf *bytes.Buffer) error
}
// Header is the header of a packet. It exists out of a single varuint32 which is composed of a packet ID and
// a sender and target sub client ID. These IDs are used for split screen functionality.
type Header struct {
PacketID uint32
SenderSubClient byte
TargetSubClient byte
}
// Write writes the header as a single varuint32 to buf.
func (header *Header) Write(buf *bytes.Buffer) error {
return protocol.WriteVaruint32(buf, header.PacketID|(uint32(header.SenderSubClient)<<10)|(uint32(header.TargetSubClient)<<12))
}
// Read reads a varuint32 from buf and sets the corresponding values to the Header.
func (header *Header) Read(buf *bytes.Buffer) error {
var value uint32
if err := protocol.Varuint32(buf, &value); err != nil {
return err
}
header.PacketID = value & 0x3FF
header.SenderSubClient = byte((value >> 10) & 0x3)
header.TargetSubClient = byte((value >> 12) & 0x3)
return nil
}