-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
100 lines (92 loc) · 2.48 KB
/
helpers.go
File metadata and controls
100 lines (92 loc) · 2.48 KB
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
package pecs
import (
"github.com/df-mc/dragonfly/server/cmd"
"github.com/df-mc/dragonfly/server/item"
"github.com/df-mc/dragonfly/server/player"
"github.com/df-mc/dragonfly/server/player/form"
)
// getSessionFromPlayer extracts the session from a player's handler.
// Returns nil if the player doesn't have a PECS SessionHandler.
func getSessionFromPlayer(p *player.Player) *Session {
h, ok := p.Handler().(*SessionHandler)
if !ok {
return nil
}
return h.session
}
// Command extracts the player and session from a command source.
// Returns (nil, nil) if the source is not a player or has no session.
//
// Usage:
//
// func (c MyCommand) Run(src cmd.Source, out *cmd.Output, tx *world.Tx) {
// p, sess := pecs.Command(src)
// if sess == nil {
// out.Error("Player-only command")
// return
// }
//
// // Use p and sess...
// }
//
// Concurrency:
// Commands are executed synchronously with the player, just like handlers.
// It is safe to access and modify components directly.
func Command(src cmd.Source) (*player.Player, *Session) {
p, ok := src.(*player.Player)
if !ok {
return nil, nil
}
sess := getSessionFromPlayer(p)
return p, sess
}
// Form extracts the player and session from a form submitter.
// Returns (nil, nil) if the submitter is not a player or has no session.
//
// Usage:
//
// func (f MyForm) Submit(sub form.Submitter, tx *world.Tx) {
// p, sess := pecs.Form(sub)
// if sess == nil {
// return
// }
//
// // Use p and sess...
// }
//
// Concurrency:
// Form submissions are executed synchronously with the player, just like handlers.
// It is safe to access and modify components directly.
func Form(sub form.Submitter) (*player.Player, *Session) {
p, ok := sub.(*player.Player)
if !ok {
return nil, nil
}
sess := getSessionFromPlayer(p)
return p, sess
}
// Item extracts the player and session from an item user.
// Returns (nil, nil) if the user is not a player or has no session.
//
// Usage:
//
// func (i MyItem) Use(tx *world.Tx, user item.User, ctx *item.UseContext) bool {
// p, sess := pecs.Item(user)
// if sess == nil {
// return
// }
//
// // Use p and sess...
// }
//
// Concurrency:
// Item uses are executed synchronously with the player, just like handlers.
// It is safe to access and modify components directly.
func Item(user item.User) (*player.Player, *Session) {
p, ok := user.(*player.Player)
if !ok {
return nil, nil
}
sess := getSessionFromPlayer(p)
return p, sess
}