-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
96 lines (75 loc) · 1.82 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"syscall/js"
dem "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs"
common "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/common"
)
const (
// WASM doesn't enjoy the big buffer sizes allocated by default
msgQueueBufferSize = 128 * 1024
)
func main() {
c := make(chan struct{}, 0)
dem.DefaultParserConfig = dem.ParserConfig{
MsgQueueBufferSize: msgQueueBufferSize,
}
registerCallbacks()
fmt.Println("WASM Go Initialized")
<-c
}
func registerCallbacks() {
js.Global().Set("parse", js.FuncOf(parse))
}
func uint8ArrayToBytes(value js.Value) []byte {
s := make([]byte, value.Get("byteLength").Int())
js.CopyBytesToGo(s, value)
return s
}
func parse(this js.Value, args []js.Value) interface{} {
parseInternal(args[0], args[1])
return nil
}
func parseInternal(data js.Value, callback js.Value) {
b := bytes.NewBuffer(uint8ArrayToBytes(data))
parser := dem.NewParser(b)
header, err := parser.ParseHeader()
checkError(err)
// TODO: report headerpointer error
//fmt.Println("Header:", header)
fmt.Println("map: " + header.MapName)
err = parser.ParseToEnd()
checkError(err)
fmt.Println("parsed")
players := parser.GameState().Participants().Playing()
var stats []playerStats
for _, p := range players {
stats = append(stats, statsFor(p))
}
bStats, err := json.Marshal(stats)
checkError(err)
// Return result to JS
callback.Invoke(string(bStats))
}
type playerStats struct {
Name string `json:"name"`
Kills int `json:"kills"`
Deaths int `json:"deaths"`
Assists int `json:"assists"`
}
func statsFor(p *common.Player) playerStats {
return playerStats{
Name: p.Name,
Kills: p.Kills(),
Deaths: p.Deaths(),
Assists: p.Assists(),
}
}
func checkError(err error) {
if err != nil {
log.Panic(err)
}
}