Files
aeternalis/server/internal/game/crafting.go
T

316 lines
10 KiB
Go

package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"errors"
"fmt"
"maps"
"math"
"slices"
"strings"
)
func (w *World) refreshCrafting(c *Character) {
for id, name := range (content.Catalog{Building: w.Balance.Building}).BuildingItems() {
if c.View.Inventory[id] > 0 {
c.View.StackNames[id] = name
}
}
if c.View.Crafting == nil {
c.View.Crafting = map[string]p.CraftProgress{}
}
if c.View.DiscoveredRecipes == nil {
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
}
if w.Balance.Crafting == nil {
return
}
for _, s := range w.Balance.Crafting.Professions {
v := c.View.Crafting[s.ID]
v.ID = s.ID
v.Name = s.Name
v.Level, v.XPToNextLevel = content.SkillLevel(s, v.XP)
v.LossPercent = w.Balance.Crafting.Rules.Loss(v.Level)
c.View.Crafting[s.ID] = v
}
for _, m := range w.Balance.Crafting.Materials {
if c.View.Inventory[m.ID] > 0 {
c.View.StackNames[m.ID] = m.Name
}
}
}
func (w *World) restoreCrafting(c *Character) error {
if !finiteCraft(c.ItemReadyAt) {
return errors.New("invalid item cooldown")
}
if len(c.View.Crafting) > 64 || len(c.View.DiscoveredRecipes) > 512 || math.IsNaN(c.CraftReadyAt) || math.IsInf(c.CraftReadyAt, 0) || c.CraftReadyAt < 0 {
return errors.New("invalid crafting history")
}
for _, v := range c.View.Crafting {
if v.XP < 0 || v.XP > 10000000000000 {
return errors.New("invalid crafting experience")
}
}
for id, r := range c.View.DiscoveredRecipes {
if id != r.Recipe.ID || r.Recipe.Revision < 1 || len(r.Recipe.Inputs) > 16 || len(r.Recipe.Outputs) > 8 || len(r.Recipe.Name) > 80 {
return errors.New("invalid discovered recipe")
}
}
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{})
}
func ValidateCraftedStacks(inventory map[string]int64, batches []p.CraftedStack, seen map[string]bool) error {
if len(batches) > 2048 {
return errors.New("too many crafted batches")
}
totals := map[string]int64{}
for _, b := range batches {
if b.ID == "" || len(b.ID) > 100 || seen[b.ID] || b.Item == "" || b.Quantity < 1 || b.Quantity > 1000000000000 || !validProvenance(b.Provenance) {
return errors.New("invalid crafted provenance or batch")
}
seen[b.ID] = true
totals[b.Item] += b.Quantity
if totals[b.Item] > inventory[b.Item] {
return errors.New("crafted batches exceed inventory")
}
}
return nil
}
func finiteCraft(n float64) bool { return !math.IsNaN(n) && !math.IsInf(n, 0) && n >= 0 }
func validProvenance(v p.CraftProvenance) bool {
return len(v.CharacterID) == 32 && v.CrafterName != "" && len(v.CrafterName) <= 80 && v.WorldID != "" && len(v.WorldID) <= 128 && v.RecipeID != "" && len(v.RecipeID) <= 64 && v.RecipeRevision >= 1 && v.Profession != "" && len(v.Profession) <= 64 && v.Level >= 1 && v.Level <= 1000 && finiteCraft(v.At)
}
// Consume unmarked units first, then crafted batches in acquisition order.
// Splits receive a new batch identity; surviving units retain their provenance.
func TakeStack(c *Character, item string, quantity int64) []p.CraftedStack {
crafted := int64(0)
for _, b := range c.View.CraftedStacks {
if b.Item == item {
crafted += b.Quantity
}
}
remaining := quantity - min(quantity, max(0, c.View.Inventory[item]-crafted))
taken := []p.CraftedStack{}
kept := []p.CraftedStack{}
for _, b := range c.View.CraftedStacks {
if b.Item == item && remaining > 0 {
n := min(remaining, b.Quantity)
part := b
part.Quantity = n
if n < b.Quantity {
part.ID = ID()
}
taken = append(taken, part)
b.Quantity -= n
remaining -= n
}
if b.Quantity > 0 {
kept = append(kept, b)
}
}
c.View.CraftedStacks = kept
c.View.Inventory[item] -= quantity
if c.View.Inventory[item] == 0 {
delete(c.View.Inventory, item)
}
return taken
}
func (w *World) checkCraftedWorld(c *Character) error {
seen := map[string]bool{}
for _, existing := range w.Characters {
if existing.View.Entity.ID == c.View.Entity.ID {
continue
}
if e := ValidateCraftedStacks(existing.View.Inventory, existing.View.CraftedStacks, seen); e != nil {
return e
}
}
for _, corpse := range w.Corpses {
if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, seen); e != nil {
return e
}
}
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, seen)
}
func (w *World) CraftProfessions(c *Character) []p.CraftProgress {
w.refreshCrafting(c)
out := []p.CraftProgress{}
for _, s := range w.Balance.Crafting.Professions {
out = append(out, c.View.Crafting[s.ID])
}
return out
}
// The browser offers quantities, never a secret recipe ID. Invalid inventory or
// requirement requests do not consume materials or advance the random stream.
func (w *World) AttemptCraft(c *Character, req p.CraftRequest) (p.CraftResult, error) {
result := p.CraftResult{ID: req.ID, Consumed: map[string]int64{}, Created: []string{}}
if c == nil || HouseID(c) != "" || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
return result, errors.New("character cannot craft")
}
now := float64(w.now.UnixMilli()) / 1000
if now < c.CraftReadyAt {
return result, errors.New("crafting cooldown")
}
if len(req.Ingredients) < 1 || len(req.Ingredients) > 16 {
return result, errors.New("offer 1-16 distinct ingredients")
}
v := w.Balance.Crafting
profession := slices.IndexFunc(v.Professions, func(s content.GatheringSkill) bool { return s.ID == req.Profession })
if profession < 0 {
return result, errors.New("unknown crafting profession")
}
for id, n := range req.Ingredients {
if id == "" || len(id) > 64 || n < 1 || n > 1000 || c.View.Inventory[id] < n {
return result, errors.New("invalid or missing ingredients")
}
}
w.refreshCrafting(c)
progress := c.View.Crafting[req.Profession]
var recipe *content.CraftRecipe
for _, r := range v.Recipes {
if r.Profession == req.Profession && maps.Equal(r.Inputs, req.Ingredients) {
copy := r
recipe = &copy
break
}
}
if recipe != nil {
stats := w.statValues(c, false)
for key, n := range recipe.Stats {
if stats[key].Final < n {
return result, fmt.Errorf("valid recipe; requires %s %.0f (without equipment bonuses); no ingredients spent", key, n)
}
}
for _, id := range recipe.Titles {
if !slices.ContainsFunc(c.View.Titles, func(t p.TitleAward) bool { return t.ID == id }) {
return result, errors.New("valid recipe; required title missing; no ingredients spent")
}
}
}
// Results are constructed on a staged world; persistence failures never publish
// this random result or partially spend the live player's ingredients.
result.Valid = recipe != nil
if recipe != nil {
result.Success = !w.roll(v.Rules.Failure(progress.Level, recipe.Level))
}
rate := v.Rules.Loss(progress.Level)
if result.Success {
rate = 100
}
keys := slices.Sorted(maps.Keys(req.Ingredients))
for _, id := range keys {
n := int64(math.Ceil(float64(req.Ingredients[id]) * rate / 100))
n = min(req.Ingredients[id], max(1, n))
TakeStack(c, id, n)
result.Consumed[id] = n
}
if recipe != nil {
var known p.CraftRecipe
raw, _ := json.Marshal(recipe)
_ = json.Unmarshal(raw, &known)
discovered := p.KnownRecipe{Recipe: known, DiscoveredAt: now}
if old, ok := c.View.DiscoveredRecipes[recipe.ID]; ok && old.Recipe.Revision == recipe.Revision {
discovered.DiscoveredAt = old.DiscoveredAt
}
c.View.DiscoveredRecipes[recipe.ID] = discovered
result.Recipe = &discovered
}
if result.Success {
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: recipe.ID, RecipeRevision: recipe.Revision, Profession: req.Profession, Level: progress.Level, At: now}
for _, id := range slices.Sorted(maps.Keys(recipe.Outputs)) {
n := recipe.Outputs[id]
before := len(c.View.Items)
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, id, n); err != nil {
return result, err
}
if len(c.View.Items) > before {
var definition content.ItemDefinition
for _, d := range w.Balance.Items {
if d.ID == id {
definition = d
break
}
}
for i := before; i < len(c.View.Items); i++ {
item := &c.View.Items[i]
copy := provenance
item.Provenance = &copy
item.Modifiers = append(item.Modifiers, w.craftModifiers(definition, progress.Level)...)
result.Created = append(result.Created, item.ID)
}
} else {
batch := p.CraftedStack{ID: ID(), Item: id, Quantity: n, Provenance: provenance}
c.View.CraftedStacks = append(c.View.CraftedStacks, batch)
result.Created = append(result.Created, batch.ID)
}
}
if w.AllowsXP() {
progress.XP = min(int64(10000000000000), progress.XP+recipe.XP)
c.View.Crafting[req.Profession] = progress
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
w.grantXP(c, w.Balance.Progression.CraftXP)
}
result.Message = "Crafted " + recipe.Name
} else if recipe != nil {
result.Message = "Valid recipe discovered: " + recipe.Name + ". Craft failed; some ingredients were lost."
} else {
result.Message = "No recipe matches this combination. Some ingredients were lost."
}
if err := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{}); err != nil {
return result, err
}
c.CraftReadyAt = now + v.Rules.Cooldown
c.Message = result.Message
w.RefreshStats(c)
w.evaluateTitles(c)
w.dirty = true
return result, nil
}
func (w *World) craftModifiers(item content.ItemDefinition, level int64) []p.StatModifier {
pool := slices.Clone(item.CraftPool)
out := []p.StatModifier{}
bias := math.Min(w.Balance.Crafting.Rules.MaxQualityBias, 1+float64(level-1)*w.Balance.Crafting.Rules.QualityPerLevel)
for range item.CraftRolls {
total := float64(0)
for _, s := range pool {
total += s.Weight
}
pick := w.randomUnit() * total
index := len(pool) - 1
for i, s := range pool {
pick -= s.Weight
if pick < 0 {
index = i
break
}
}
s := pool[index]
pool = append(pool[:index], pool[index+1:]...)
value := math.Round((s.Min+(s.Max-s.Min)*math.Pow(w.randomUnit(), 1/bias))*100) / 100
m := p.StatModifier{Stat: s.Stat}
if s.Percent {
m.Percent = value
} else {
m.Flat = value
}
out = append(out, m)
}
return out
}
func ValidCraftRequest(r p.CraftRequest) bool {
if len(r.ID) < 32 || len(r.ID) > 36 || len(r.CharacterID) != 32 || len(r.Profession) > 64 {
return false
}
for _, id := range []string{r.ID, r.CharacterID} {
if strings.Trim(id, "0123456789abcdef-") != "" {
return false
}
}
return true
}