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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
package behavior
import (
"fmt"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"gopkg.in/yaml.v3"
)
// excludedContentPath reports whether path lies under a directory or file
// whose name starts with "_", relative to root. That is the project's
// convention for work-in-progress content that must not be loaded, validated,
// indexed, or published while a builder is still authoring it.
func excludedContentPath(root, path string) bool {
rel, err := filepath.Rel(root, path)
if err != nil {
return false
}
for _, part := range strings.Split(rel, string(os.PathSeparator)) {
if strings.HasPrefix(part, "_") {
return true
}
}
return false
}
func BuildPathIndex(dir string) map[string]string {
index := make(map[string]string)
filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
id, ok := yamlID(d.Name())
if !ok {
return nil
}
if excludedContentPath(dir, path) {
return nil
}
index[id] = path
return nil
})
return index
}
func BuildRoomIndex(dir string) map[int]string {
index := make(map[int]string)
filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
id, ok := yamlID(d.Name())
if !ok {
return nil
}
if excludedContentPath(dir, path) {
return nil
}
n, convErr := strconv.Atoi(id)
if convErr != nil {
// A non-numeric filename (for example a "1001_copy.yaml"
// backup) must never shadow a real room via a numeric prefix;
// skip it here and let validation flag it.
return nil
}
// Room IDs are positive; every other code path treats <= 0 as "no
// room". A 0.yaml/-1.yaml must not become a real room.
if n <= 0 {
return nil
}
index[n] = path
return nil
})
return index
}
func WalkYAMLDir(dir string, fn func(path, id string, data []byte) error) error {
return filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
// A missing root is an empty tree; any other walk error (for
// example an unreadable directory) must surface instead of
// silently validating nothing.
if os.IsNotExist(err) {
return nil
}
return err
}
if d.IsDir() {
return nil
}
id, ok := yamlID(d.Name())
if !ok {
return nil
}
if excludedContentPath(dir, path) {
return nil
}
data, readErr := os.ReadFile(path)
if readErr != nil {
if os.IsNotExist(readErr) {
return nil
}
return readErr
}
return fn(path, id, data)
})
}
// yamlID returns the id (filename without extension) for a .yaml or .yml file.
// The runtime trigger loader accepts .yml, so validation discovery must too,
// otherwise such a file loads and fires while every check ignores it.
func yamlID(name string) (string, bool) {
if strings.HasSuffix(name, ".yaml") {
return strings.TrimSuffix(name, ".yaml"), true
}
if strings.HasSuffix(name, ".yml") {
return strings.TrimSuffix(name, ".yml"), true
}
return "", false
}
type Duplicate struct {
ID string
Paths []string
}
func CheckDuplicateIDs(dir string) []Duplicate {
seen := make(map[string][]string)
filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
id, ok := yamlID(d.Name())
if !ok {
return nil
}
if excludedContentPath(dir, path) {
return nil
}
seen[id] = append(seen[id], path)
return nil
})
var dups []Duplicate
for id, paths := range seen {
if len(paths) > 1 {
dups = append(dups, Duplicate{ID: id, Paths: paths})
}
}
return dups
}
func SuccessChance(cfg SuccessFormula, level int, requiredLevel int) float64 {
chance := cfg.Base + float64(level-requiredLevel)*cfg.PerLevel
if chance > cfg.Cap {
chance = cfg.Cap
}
if chance < 0 {
chance = 0
}
return chance
}
var (
dropIndexes = map[string]map[string]string{}
dropIndexMu sync.Mutex
)
func loadDropIndex(dataDir string) map[string]string {
dropIndexMu.Lock()
defer dropIndexMu.Unlock()
// Keyed by dataDir: a single process can host more than one data dir
// (tests), and a shared index would resolve ids against the first one.
if idx, ok := dropIndexes[dataDir]; ok {
return idx
}
idx := BuildPathIndex(filepath.Join(dataDir, "drops"))
dropIndexes[dataDir] = idx
return idx
}
func ClearDropIndex() {
dropIndexMu.Lock()
defer dropIndexMu.Unlock()
dropIndexes = map[string]map[string]string{}
}
func LoadDropTable(dataDir, id string) (*DropTableDef, error) {
index := loadDropIndex(dataDir)
path, ok := index[id]
if !ok {
if id == "" || strings.Contains(id, "..") || strings.ContainsAny(id, `/\`) {
return nil, fmt.Errorf("invalid drop table id %q", id)
}
path = filepath.Join(dataDir, "drops", id+".yaml")
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read drop table %s: %w", id, err)
}
var dt DropTableDef
if err := yaml.Unmarshal(data, &dt); err != nil {
return nil, fmt.Errorf("parse drop table %s: %w", id, err)
}
return &dt, nil
}
// pickWeighted returns a single entry chosen by weight, without resolving any
// table reference on it. Returns nil if the list is empty or has no weight.
func pickWeighted(drops []DropEntry) *DropEntry {
if len(drops) == 0 {
return nil
}
total := 0
for _, d := range drops {
total += d.Weight
}
if total <= 0 {
return nil
}
roll := rand.Intn(total)
cumulative := 0
for i := range drops {
cumulative += drops[i].Weight
if roll < cumulative {
return &drops[i]
}
}
return &drops[0]
}
// maxDropTableDepth bounds sub-table recursion. A self- or mutual-reference
// in authored drop tables would otherwise recurse until the goroutine stack
// is exhausted (an unrecoverable fatal error); the validator also rejects
// cycles at startup.
const maxDropTableDepth = 32
// maxDropRolls bounds a table-reference entry's `quantity` (how many times the
// referenced table is rolled). An accidental large value would run that many
// weighted picks on the owner tick and stall the whole world.
const maxDropRolls = 64
func ResolveDrop(dataDir string, drops []DropEntry) *DropEntry {
return resolveDrop(dataDir, drops, 0)
}
func resolveDrop(dataDir string, drops []DropEntry, depth int) *DropEntry {
if depth > maxDropTableDepth {
return nil
}
picked := pickWeighted(drops)
if picked == nil {
return nil
}
if picked.Table != "" {
sub, err := LoadDropTable(dataDir, picked.Table)
if err != nil {
return nil
}
resolved := resolveDrop(dataDir, sub.Drops, depth+1)
if resolved == nil {
return nil
}
qty := picked.Quantity
if qty <= 0 {
qty = resolved.Quantity
}
if qty <= 0 {
qty = 1
}
return &DropEntry{
ItemID: resolved.ItemID,
Quantity: qty,
Depletes: picked.Depletes,
SuccessMessage: picked.SuccessMessage,
Tool: picked.Tool,
Level: picked.Level,
XP: picked.XP,
}
}
return picked
}
// ResolveDropList performs one weighted pick from drops. A plain item entry
// yields a single result. When the picked entry references a sub-table, its
// Quantity is treated as the number of INDEPENDENT rolls against that sub-table
// (default 1) — each roll may produce a different item — and all results are
// returned. Tables are just weighted lists of items; this is skill-independent.
func ResolveDropList(dataDir string, drops []DropEntry) []DropEntry {
return resolveDropList(dataDir, drops, 0)
}
func resolveDropList(dataDir string, drops []DropEntry, depth int) []DropEntry {
if depth > maxDropTableDepth {
return nil
}
picked := pickWeighted(drops)
if picked == nil {
return nil
}
if picked.Table == "" {
return []DropEntry{*picked}
}
sub, err := LoadDropTable(dataDir, picked.Table)
if err != nil {
return nil
}
rolls := picked.Quantity
if rolls <= 0 {
rolls = 1
}
// Bound authored quantities: an accidental `quantity: 1000000000` on a
// table reference would otherwise run a billion weighted picks on the
// owner tick and stall the whole world.
if rolls > maxDropRolls {
rolls = maxDropRolls
}
var out []DropEntry
for i := 0; i < rolls; i++ {
if resolved := resolveDrop(dataDir, sub.Drops, depth+1); resolved != nil && resolved.ItemID != "" {
out = append(out, *resolved)
}
}
return out
}
|