feat(all): adapt gameplay and account state to 2.37.13
Update game mappings, resource versions, schedules, seeds and plugin targets for 2.37.13. Use global instance identities for inventory, equipment, story characters and borrowed supporters. Unify mission conditions and progression across battles, equipment, events, fishing and account state. Complete pack purchase, reward, exploration, replay and introduction flows; reconcile starter rewards and profile unlocks. Correct gacha discounts, sequential shop packages, restaurant and dating progression. Restore friend presence, virtual-square realtime rooms, arena costume costs and guild raid settlement.
This commit is contained in:
1 parent
6f00e1a53e
commit
91a5e1fb26
234 files changed
+8906
-1980
No files matched your search
+2
-2
@@ -135,8 +135,8 @@ TLS 证书、缓存容量、访问日志和服务条款由服主负责。公网
|
||||
`<bundle_version>` 和 `<game_data_version>` 必须分别等于客户端包内 `versions.json` 的 `bundle_version` 与 `game_data_version`。例如当前发布版本对应:
|
||||
|
||||
```text
|
||||
ServerData/StandaloneWindows64/HD/20261007175947/
|
||||
GameData/20261008155037/
|
||||
ServerData/StandaloneWindows64/HD/20261022174708/
|
||||
GameData/20261021182514/
|
||||
```
|
||||
|
||||
准备完成后,在 `bd2client` 中选择“本地已下载资源”,并选中最外层的 `<本地资源根目录>`,不要直接选择 `ServerData`、`GameData` 或某个版本号目录。客户端会验证目录结构和版本,然后由 LI 插件在游戏进程内把该目录作为仅监听 loopback 的本机资源源提供给游戏。校验失败时需要玩家自行修正或重新准备资源,客户端不会跨版本拼接或自动从网络补齐缺失文件。
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
|
||||
func guideStepOne(t *testing.T, g *missionGameplay) (map[uint64]bool, uint64) {
|
||||
t.Helper()
|
||||
design := g.factory.design.eventTasksDesign
|
||||
groups := map[uint64]bool{}
|
||||
var passID uint64
|
||||
for id, pass := range design.Passes {
|
||||
if pass.ScheduleType != 0 || pass.NewbieGroup == 0 || pass.NewbieStep != 1 {
|
||||
continue
|
||||
}
|
||||
if passID == 0 {
|
||||
passID = id
|
||||
}
|
||||
for _, group := range design.MissionGroups[pass.MissionGroup].Groups {
|
||||
groups[group] = true
|
||||
}
|
||||
}
|
||||
if passID == 0 || len(groups) == 0 {
|
||||
t.Fatal("GameData has no guide pass step 1")
|
||||
}
|
||||
return groups, passID
|
||||
}
|
||||
|
||||
func guideConditionMission(t *testing.T, g *missionGameplay, groups map[uint64]bool, condition, subtype uint64) ([]byte, uint64) {
|
||||
t.Helper()
|
||||
design := g.factory.design.eventTasksDesign
|
||||
for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
|
||||
task, found := design.Missions[appValue(row, 3)]
|
||||
if found && groups[task.Group] && task.Type == condition && task.SubType == subtype {
|
||||
return row, task.ID
|
||||
}
|
||||
}
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// clearEventMissions keeps durable reward claims but removes every derived
|
||||
// mission value, reproducing an account that claimed before the pass existed.
|
||||
func clearEventMissions(t *testing.T, g *missionGameplay) {
|
||||
t.Helper()
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
raw, err := p.gameplayStore.Load(ctx.State, "eventtasks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var state map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state["Missions"] = json.RawMessage(`{}`)
|
||||
raw, err = json.Marshal(state)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.gameplayStore.Save(ctx.State, "eventtasks", raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
}
|
||||
|
||||
func missionTarget(t *testing.T, g *missionGameplay, id uint64) uint64 {
|
||||
t.Helper()
|
||||
target := g.factory.design.eventTasksDesign.Missions[id].Target
|
||||
if target == 0 {
|
||||
return 1
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// Define_MissionConditionType.McRewardToAchievementLevel is condition 221.
|
||||
func TestGuidePassAchievementLevelMissionDerivesFromClaimedReward(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
groups, _ := guideStepOne(t, g)
|
||||
row, id := guideConditionMission(t, g, groups, 221, 1)
|
||||
if row == nil {
|
||||
t.Fatal("achievement level mission missing from EventMissionInfo")
|
||||
}
|
||||
want := missionTarget(t, g, id)
|
||||
if got := appValue(row, 4); got != 0 {
|
||||
t.Fatalf("achievement level mission started at %d, want 0", got)
|
||||
}
|
||||
g.call("/UserLevelReward", appScalar(2, 1))
|
||||
clearEventMissions(t, g)
|
||||
row, _ = guideConditionMission(t, g, groups, 221, 1)
|
||||
if row == nil {
|
||||
t.Fatal("achievement level mission disappeared after claiming")
|
||||
}
|
||||
if got := appValue(row, 4); got != want {
|
||||
t.Fatalf("achievement level mission value=%d, want %d", got, want)
|
||||
}
|
||||
if again, _ := guideConditionMission(t, g, groups, 221, 1); appValue(again, 4) != want {
|
||||
t.Fatalf("repeated reconciliation changed mission value to %d", appValue(again, 4))
|
||||
}
|
||||
}
|
||||
|
||||
// Define_MissionConditionType.McRewardToPassLevel is condition 223.
|
||||
func TestGuidePassPassLevelMissionDerivesFromClaimedReward(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
groups, passID := guideStepOne(t, g)
|
||||
row, id := guideConditionMission(t, g, groups, 223, 1)
|
||||
if row == nil {
|
||||
t.Fatal("pass level mission missing from EventMissionInfo")
|
||||
}
|
||||
want := missionTarget(t, g, id)
|
||||
if got := appValue(row, 4); got != 0 {
|
||||
t.Fatalf("pass level mission started at %d, want 0", got)
|
||||
}
|
||||
g.call("/PassReward", append(appScalar(3, passID), appScalar(4, 1)...))
|
||||
clearEventMissions(t, g)
|
||||
row, _ = guideConditionMission(t, g, groups, 223, 1)
|
||||
if row == nil {
|
||||
t.Fatal("pass level mission disappeared after claiming")
|
||||
}
|
||||
if got := appValue(row, 4); got != want {
|
||||
t.Fatalf("pass level mission value=%d, want %d", got, want)
|
||||
}
|
||||
if again, _ := guideConditionMission(t, g, groups, 223, 1); appValue(again, 4) != want {
|
||||
t.Fatalf("repeated reconciliation changed mission value to %d", appValue(again, 4))
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func TestAchievementReconcileHistoricalCompoundTitleRequiresClaim(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
c := command.Context{State: tx}
|
||||
c := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
var costume roster.Costume
|
||||
for _, owned := range p.collection.Costumes() {
|
||||
if p.design.costumePotentialDesign.CostumeUnique[owned.ID] == 1 {
|
||||
@@ -180,7 +180,7 @@ func TestAchievementReconcilePreservesLargerHistoryAndCountsNewGrantOnce(t *test
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
c := command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "history-grant"}, State: tx}
|
||||
c := command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "history-grant"}, State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
request := wire.AppendVarint(nil, 1, 77)
|
||||
observer := g.owner.assembly.achievementObserver
|
||||
if err := observer.BeforeDispatch(c, "/GachaBuy", request); err != nil {
|
||||
|
||||
@@ -13,10 +13,11 @@ import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
func TestFirstAvatarChoiceAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
// AvatarPacket buys a character and its authored outfit before AvatarSave.
|
||||
// Current GameData: shop 1 costs 1000 type44 and grants char 1 with
|
||||
// hair 10001, outfit 40001, head accessory 20001. Motion 100001 is free.
|
||||
// Current GameData: shop 1's nominal price is 1000 type44 and grants char1
|
||||
// with hair10001, outfit40001, head20001. The server's first-choice policy
|
||||
// waives that price once; later purchases retain the authored prices.
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
@@ -34,7 +35,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx}
|
||||
ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
if _, err = g.owner.assembly.eventEconomy.Apply(ctx, "avatar-test-budget", nil, []gamedata.Reward{{Type: 44, Count: 2500}}); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
@@ -49,8 +50,8 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
product = wire.AppendBytes(product, 2, price)
|
||||
buy := g.request("/AvatarShopBuy", wire.AppendBytes(nil, 2, product))
|
||||
g.execute(buy, false)
|
||||
if got := g.wordCurrency(); got != budget-1000 {
|
||||
t.Fatalf("avatar purchase balance=%d want %d", got, budget-1000)
|
||||
if got := g.wordCurrency(); got != budget {
|
||||
t.Fatalf("first choice changed balance=%d want %d", got, budget)
|
||||
}
|
||||
for _, asset := range [][2]uint64{{61, 1}, {49, 10001}, {49, 20001}, {49, 40001}} {
|
||||
if g.itemCount(asset[0], asset[1]) != 1 {
|
||||
@@ -58,7 +59,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
}
|
||||
}
|
||||
g.execute(buy, false)
|
||||
if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 {
|
||||
if g.wordCurrency() != budget || g.itemCount(61, 1) != 1 {
|
||||
t.Fatal("replayed avatar purchase charged or granted again")
|
||||
}
|
||||
unowned := wire.AppendVarint(nil, 1, 1)
|
||||
@@ -70,11 +71,11 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
use = wire.AppendVarint(use, 5, 40001)
|
||||
g.call("/AvatarSave", wire.AppendBytes(nil, 2, use))
|
||||
g.call("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001))
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 {
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget {
|
||||
t.Fatal("free motion was not granted without currency consumption")
|
||||
}
|
||||
g.execute(g.request("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001)), true)
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 {
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget {
|
||||
t.Fatal("repeated free motion changed ownership or charged currency")
|
||||
}
|
||||
wishlist := wire.AppendVarint(nil, 2, 40015)
|
||||
@@ -150,7 +151,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
if len(decodeWishlist(list)) != 0 {
|
||||
t.Fatal("wishlist removal did not clear the persisted list")
|
||||
}
|
||||
if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 || g.itemCount(50, 100001) != 1 {
|
||||
if g.wordCurrency() != budget || g.itemCount(61, 1) != 1 || g.itemCount(50, 100001) != 1 {
|
||||
t.Fatal("reopening or profile queries changed purchased assets")
|
||||
}
|
||||
}
|
||||
@@ -211,7 +212,7 @@ func TestAvatarDiamondPurchaseAndInvalidEquipmentBatchRemainAtomic(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, "avatar-batch-and-collab-budget", nil, []gamedata.Reward{{Type: 44, Count: 2000}, {Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 40015, Count: 1}}); err != nil {
|
||||
if _, err = g.owner.assembly.eventEconomy.Apply(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, "avatar-batch-and-collab-budget", nil, []gamedata.Reward{{Type: 44, Count: 2000}, {Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 40015, Count: 1}}); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
|
||||
// GameFieldManager.IEnteredCafeteriaPackField claims the introduction on every
|
||||
// cafeteria entry while ContentUnlockDating (ContentOpenTable group19/detail1)
|
||||
// lacks its ticket. Current GameData: CafeteriaDefaultTable rewards RandomBox
|
||||
// 1400001, whose dropType1 RewardGroup holds that ticket (3007) and LobbyDeco 26.
|
||||
func TestCafeteriaIntroductionDeliversTheDatingTicketOnce(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
ticket := g.owner.assembly.design.contentOpeningDesign.Dating.TicketID
|
||||
if ticket == 0 {
|
||||
t.Fatal("GameData dating opening rule has no ticket")
|
||||
}
|
||||
if got := g.itemCount(19, ticket); got != 0 {
|
||||
t.Fatalf("dating ticket owned before the introduction: %d", got)
|
||||
}
|
||||
g.call("/CafeteriaIntroductionStoryReward", nil)
|
||||
if got := g.itemCount(19, ticket); got != 1 {
|
||||
t.Fatalf("introduction delivered dating ticket count %d, want 1", got)
|
||||
}
|
||||
if got := g.itemCount(25, 26); got != 1 {
|
||||
t.Fatalf("introduction delivered lobby decoration count %d, want 1", got)
|
||||
}
|
||||
g.call("/CafeteriaIntroductionStoryReward", nil)
|
||||
if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 1 || deco != 1 {
|
||||
t.Fatalf("repeated introduction claim changed rewards: ticket %d decoration %d", got, deco)
|
||||
}
|
||||
}
|
||||
|
||||
// Accounts whose introduction was recorded without the ticket regain it at
|
||||
// login exactly once; the introduction box is not granted a second time.
|
||||
func TestCafeteriaLoginRestoresAMissingDatingTicketOnce(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
ticket := g.owner.assembly.design.contentOpeningDesign.Dating.TicketID
|
||||
g.call("/CafeteriaInfo", nil)
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
raw, err := p.gameplayStore.Load(ctx.State, "cafeteria")
|
||||
if err != nil || raw == nil {
|
||||
t.Fatalf("cafeteria state missing: %v", err)
|
||||
}
|
||||
var state map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state["Introduction"] = json.RawMessage("true")
|
||||
if raw, err = json.Marshal(state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.gameplayStore.Save(ctx.State, "cafeteria", raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
if got := g.itemCount(19, ticket); got != 0 {
|
||||
t.Fatalf("ticket restored before login: %d", got)
|
||||
}
|
||||
g.call("/LoginUser", nil)
|
||||
if got := g.itemCount(19, ticket); got != 1 {
|
||||
t.Fatalf("login restored dating ticket count %d, want 1", got)
|
||||
}
|
||||
if got := g.itemCount(25, 26); got != 0 {
|
||||
t.Fatalf("login restoration regranted the introduction box: decoration %d", got)
|
||||
}
|
||||
// Spend the restored ticket: the restoration identity must not grant again.
|
||||
s = &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
items, err := p.ownedItems.SelectMutable(ctx, 19, ticket, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.ownedItems.Consume(ctx, items); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
g.call("/LoginUser", nil)
|
||||
g.call("/CafeteriaIntroductionStoryReward", nil)
|
||||
if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 0 || deco != 0 {
|
||||
t.Fatalf("restoration repeated or regranted the box: ticket %d decoration %d", got, deco)
|
||||
}
|
||||
}
|
||||
|
||||
// MissionTable 301/3012 is guide STEP McPackQuestIdClear for pack1 quest3
|
||||
// (subType=pack, params=quest). A quest cleared without any live event, as
|
||||
// before this task existed, must still let the step be claimed.
|
||||
func TestStepQuestClearMissionCountsAlreadyClearedQuests(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
claim := append(appScalar(3, 2), appScalar(4, 301)...)
|
||||
claim = append(claim, appScalar(5, 3012)...)
|
||||
claim = append(claim, appScalar(6, 7001)...) // guide schedule, as in guide_pass_integration_test.go
|
||||
if _, err := g.execute("/MissionClear", claim); err == nil {
|
||||
t.Fatal("step claimed before pack1 quest3 was cleared")
|
||||
}
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
// The same quest number in another pack, and another pack1 quest, are not it.
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if err := p.progressState.ClearQuest(ctx, 3, 2, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.progressState.ClearQuest(ctx, 4, 1, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if _, err := g.execute("/MissionClear", claim); err == nil {
|
||||
t.Fatal("step claimed from a quest other than pack1 quest3")
|
||||
}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if err := p.progressState.ClearQuest(ctx, 3, 1, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if _, err := g.execute("/MissionClear", claim); err != nil {
|
||||
t.Fatalf("step not claimable after pack1 quest3 was cleared: %v", err)
|
||||
}
|
||||
if _, err := g.execute("/MissionClear", claim); err == nil {
|
||||
t.Fatal("step claimed twice")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// Current official PackageUI148.prefab uses BundleGroupPackageUI, whose
|
||||
// per-product buttons only check availability and that product's own limit.
|
||||
// Its contentsGroup91 sort3 product236 can be bought before sort2 product235.
|
||||
// PackageUI132 uses BundleGroupRelayPackageUI and does enforce stage order.
|
||||
func TestIndependentCashPackageCanBeBoughtBeforeEarlierDisplayItems(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
profileGrant(g, gamedata.Reward{Type: 2, Count: 1000000})
|
||||
before := g.owner.assembly.wallet.Snapshot(command.Context{}).Jewelry
|
||||
key := gamedata.CashProductKey{GroupID: 310001, ProductID: 236}
|
||||
quote, err := g.owner.assembly.cashCatalog.Quote(key, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := wire.AppendVarint(wire.AppendVarint(nil, 1, key.ProductID), 3, 1)
|
||||
pay := "98236"
|
||||
billing := wire.AppendString(wire.AppendString(nil, 1, pay), 2, fmt.Sprintf("bd2-local-commerce-v1:%s:%d:%d", pay, quote.ItemType, quote.Cost))
|
||||
request := wire.AppendBytes(wire.AppendBytes(wire.AppendVarint(nil, 3, key.GroupID), 4, line), 7, billing)
|
||||
g.call("/CashShopBuy", request)
|
||||
assertPurchase := func() {
|
||||
t.Helper()
|
||||
if got := g.owner.assembly.wallet.Snapshot(command.Context{}).Jewelry; got != before-quote.Cost {
|
||||
t.Fatalf("independent package did not debit its accepted quote once: got %d", got)
|
||||
}
|
||||
var bought, prior uint64
|
||||
for _, row := range appRows(g.call("/CashShopPurchaseCountInfo", nil), 1) {
|
||||
if appValue(row, 1) == 310001 && appValue(row, 3) == 0 {
|
||||
switch appValue(row, 2) {
|
||||
case 236:
|
||||
bought = appValue(row, 4)
|
||||
case 235:
|
||||
prior = appValue(row, 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
if bought != 1 || prior != 0 {
|
||||
t.Fatalf("purchase counts changed another display tier: bought=%d prior=%d", bought, prior)
|
||||
}
|
||||
}
|
||||
assertPurchase()
|
||||
g.reopen()
|
||||
assertPurchase()
|
||||
// A real relay's later stage remains unavailable; no quote or debit is
|
||||
// attempted until its predecessor is owned.
|
||||
var relay gamedata.CashPackageDesign
|
||||
for _, pack := range g.factory.design.cashDesign.Packages {
|
||||
if pack.ResourceName == "PackageUI132" && pack.ContentsSortID == 2 {
|
||||
relay = pack
|
||||
break
|
||||
}
|
||||
}
|
||||
if relay.ID == 0 {
|
||||
t.Fatal("official relay fixture absent")
|
||||
}
|
||||
relayLine := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, relay.ID), 2, relay.SaleGroup), 3, 1)
|
||||
failure := g.execute(g.request("/CashShopBuy", wire.AppendBytes(wire.AppendVarint(nil, 3, relay.GroupID), 4, relayLine)), true)
|
||||
if !strings.Contains(string(failure), "preceding package purchase required") {
|
||||
t.Fatalf("real relay order was not enforced: %s", failure)
|
||||
}
|
||||
assertPurchase()
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// Current 20261012190548 GameData binds Greed floor 1 to pack3003 deck10001.
|
||||
// GameData 20261021182514 binds Greed floor 1 to pack3003 deck10001.
|
||||
// Its win/no-death/8-turn challenges award material1000 x1, gold30000 and
|
||||
// bonus hunting AP5. These expectations come from the read-only GameData query,
|
||||
// independently of the castle loader and the runtime reward response.
|
||||
|
||||
@@ -184,7 +184,7 @@ func TestChatReportQuotaResetsAtNextServerDay(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: accounts[0]}, Emit: func(command.Event) error { return nil }}
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: accounts[0]}, Emit: func(command.Event) error { return nil }, InstanceIDs: factory.instanceIDs()}
|
||||
_, body, handled, err := owner.assembly.chatService.Handle(ctx, path, append(appScalar(1, 1), fields...))
|
||||
if err != nil || !handled {
|
||||
_ = tx.Rollback()
|
||||
|
||||
@@ -117,7 +117,7 @@ func TestClearPackageClaimsSurviveSessionAndDayChanges(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: account}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: account}, State: tx, InstanceIDs: factory.instanceIDs()}
|
||||
for _, quest := range factory.design.world.Story.Packs[1].MainQuestIDs {
|
||||
if err := owner.assembly.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -347,6 +347,17 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load cash products: %w", err)
|
||||
}
|
||||
for i := range d.cashDesign.Packages {
|
||||
pack := &d.cashDesign.Packages[i]
|
||||
if pack.ResourceName == "" || pack.ContentsGroupID == 0 || pack.PackageType != 2 && pack.PackageType != 8 {
|
||||
continue
|
||||
}
|
||||
layout, found := seeds.packageLayouts.Layouts[pack.ResourceName]
|
||||
if !found {
|
||||
return nil, fmt.Errorf("missing cash package layout %q", pack.ResourceName)
|
||||
}
|
||||
pack.Sequential = layout == "relay"
|
||||
}
|
||||
d.cashEntitlementDesign, err = gamedata.LoadCashEntitlementDesign(gameData, gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load cash entitlement design: %w", err)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
// PackTable in GameData 20261021182514 (tools/python/gamedata_db.py): 1001 is
|
||||
// Define_PackType 1 (Char), 2001 is 6 (Event), 3009 is 11 (Square), 3012 is
|
||||
// 14 (Life). All four open with the Edge of Dimensions ticket.
|
||||
func TestFieldPacksIncludeTicketGatedContentCards(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
packs := g.owner.assembly.design.world.FieldPacks
|
||||
for id, want := range map[int]uint64{1001: 1, 2001: 6, 3009: 11, 3012: 14} {
|
||||
pack, found := packs[id]
|
||||
if !found || pack.Type != want {
|
||||
t.Fatalf("pack %d = %+v (found %v), want type %d", id, pack, found, want)
|
||||
}
|
||||
if !pack.HasOpenRule || pack.TicketID != 11 {
|
||||
t.Fatalf("pack %d open rule = %+v, want ticket 11", id, pack)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,7 +123,7 @@ func (s *trapPlayerScenario) run(t *testing.T, commit bool, action func(command.
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "trap-client"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "trap-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()}
|
||||
action(ctx, s.owner.assembly)
|
||||
problems, err := tx.Validate()
|
||||
if err != nil || len(problems) != 0 {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FriendDBInfo field8 and GuildMemberDBInfo field10 use the same last-login
|
||||
// time. Presence is a response projection; publishing a future display time
|
||||
// must never overwrite the actual persisted login time.
|
||||
func TestFriendPresenceChangesWithoutChangingStoredLoginTime(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
registry := newPlayerRegistry(factory, time.Minute)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
b.send("/FriendAccept", appScalar(2, a.owner), 206, 0)
|
||||
stored, err := shared.friends.Profile(context.Background(), b.owner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
online := true
|
||||
shared.friends.AttachPresence(func(account string) bool { return online && account == accounts[1] })
|
||||
rows := appRows(a.send("/FriendInfoList", nil, 204, 0), 1)
|
||||
if len(rows) != 1 || appValue(rows[0], 1) != b.owner || int64(appValue(rows[0], 8)) <= time.Now().UnixMilli() {
|
||||
t.Fatal("online friend did not receive native online display marker")
|
||||
}
|
||||
persisted, err := shared.friends.Profile(context.Background(), b.owner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if persisted.LastLoginMS != stored.LastLoginMS {
|
||||
t.Fatal("online projection overwrote actual last-login time")
|
||||
}
|
||||
online = false
|
||||
rows = appRows(a.send("/FriendInfoList", nil, 204, 0), 1)
|
||||
if len(rows) != 1 || int64(appValue(rows[0], 8)) != stored.LastLoginMS {
|
||||
t.Fatal("offline friend retained online marker or lost last-login time")
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
costumeID := []uint64{101, 201}[i]
|
||||
if _, err := owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "friend-supporter-fixture", []uint64{costumeID}, factory.design.rewardCostumes); err != nil {
|
||||
if _, err := owner.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "friend-supporter-fixture", []uint64{costumeID}, factory.design.rewardCostumes); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -380,7 +380,7 @@ func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) {
|
||||
for range 2 {
|
||||
a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 0)
|
||||
}
|
||||
a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 9003)
|
||||
a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 3)
|
||||
status = b.send("/SupporterStatus", appScalar(2, 50), 438, 0)
|
||||
history = appRows(status, 1)
|
||||
if len(history) != 3 {
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestGuidePassClaimsAndExperienceSurviveWithoutEventCalendarEntry(t *testing
|
||||
assertExperience(10)
|
||||
// Reproduce the previous server's missing derived pass ledger while retaining
|
||||
// the mission reward receipt that independently proves the earned EXP.
|
||||
s := &trapPlayerScenario{owner: g.owner, account: g.account}
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
raw, err := p.gameplayStore.Load(ctx.State, "eventtasks")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/world"
|
||||
)
|
||||
|
||||
// Current QuestTable3006 has one introduction: quest1 / Quest_Main_00.
|
||||
// GameFieldManager.CoCheckGuildRaidIntroTimelineAndOpenUI completes this
|
||||
// presentation with a local watched flag, without QuestAccept or QuestClear.
|
||||
func TestGuildRaidIntroCheckpointRestartsAndCompletesWithoutQuestProgress(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
checkpoint := world.StoryCheckpoint{ID: "guild-intro-first", PackID: 3006, QuestID: 1, Phase: "accept", Timeline: "Quest_Main_00", MapID: 300603}
|
||||
if intro := factory.design.world.FieldPacks[3006].IntroQuest; intro == nil || intro.ID != 1 || intro.AcceptCinemaName != "Quest_Main_00" {
|
||||
t.Fatalf("current GameData field introduction is missing: %+v", intro)
|
||||
}
|
||||
for _, id := range []int{1001, 2001, 3001, 3003, 3004, 3005} {
|
||||
if intro := factory.design.world.FieldPacks[id].IntroQuest; intro != nil {
|
||||
t.Fatalf("ordinary field quest chain %d was misclassified as a standalone introduction: %+v", id, intro)
|
||||
}
|
||||
}
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
if _, err := p.worldService.StoryCheckpoint(ctx, world.StoryCheckpointRequest{StoryCheckpoint: checkpoint, Operation: "begin"}); !errors.Is(err, world.ErrInvalidRequest) {
|
||||
t.Fatalf("guild introduction allowed before entering its pack: %v", err)
|
||||
}
|
||||
})
|
||||
s.protocol(t, "/PackInGameInfo", trapRequest(100, 3006))
|
||||
s.position(t, 3006, 300603)
|
||||
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
for name, mutate := range map[string]func(*world.StoryCheckpoint){
|
||||
"quest": func(c *world.StoryCheckpoint) { c.QuestID = 2 },
|
||||
"difficulty": func(c *world.StoryCheckpoint) { c.Difficulty = 1 },
|
||||
"map": func(c *world.StoryCheckpoint) { c.MapID = 51 },
|
||||
"timeline": func(c *world.StoryCheckpoint) { c.Timeline = "Quest_Main_01" },
|
||||
"completion-phase": func(c *world.StoryCheckpoint) { c.Phase = "complete" },
|
||||
"object": func(c *world.StoryCheckpoint) { c.ObjectID = 1 },
|
||||
"talk": func(c *world.StoryCheckpoint) { c.SimpleTalkGroupID = 1 },
|
||||
"unknown-pack": func(c *world.StoryCheckpoint) { c.PackID = 999999 },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
candidate := checkpoint
|
||||
mutate(&candidate)
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
_, err := p.worldService.StoryCheckpoint(ctx, world.StoryCheckpointRequest{StoryCheckpoint: candidate, Operation: "begin"})
|
||||
if !errors.Is(err, world.ErrInvalidRequest) {
|
||||
t.Fatalf("invalid guild introduction accepted: %v", err)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
if pending := storyCheckpointCall(t, s.owner, "begin", checkpoint).Checkpoint; pending == nil || *pending != checkpoint {
|
||||
t.Fatalf("authored guild introduction failed to begin: %+v", pending)
|
||||
}
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending == nil || *pending != checkpoint {
|
||||
t.Fatalf("unfinished guild introduction did not survive reconnect: %+v", pending)
|
||||
}
|
||||
// Native entry restarts the cinema with a fresh request identity. It must
|
||||
// reuse the existing checkpoint rather than conflict or skip playback.
|
||||
restarted := checkpoint
|
||||
restarted.ID = "guild-intro-reconnected"
|
||||
if pending := storyCheckpointCall(t, s.owner, "begin", restarted).Checkpoint; pending == nil || *pending != checkpoint {
|
||||
t.Fatalf("restarted introduction did not reuse its pending checkpoint: %+v", pending)
|
||||
}
|
||||
if pending := storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: checkpoint.ID}).Checkpoint; pending != nil {
|
||||
t.Fatalf("cinema completion left the guild introduction pending: %+v", pending)
|
||||
}
|
||||
storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: checkpoint.ID})
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending != nil {
|
||||
t.Fatalf("completed guild introduction returned after reconnect: %+v", pending)
|
||||
}
|
||||
if s.owner.assembly.progressState.QuestCleared(1, 3006, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold {
|
||||
t.Fatal("introduction completion advanced a quest or granted rewards")
|
||||
}
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
request := append(trapRequest(101, 1), appScalar(3, 3006)...)
|
||||
if _, _, _, err := p.worldService.Handle(ctx, "/QuestClear", request); !errors.Is(err, world.ErrInvalidRequest) {
|
||||
t.Fatalf("field introduction became a claimable story quest: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
// GameData 20261012190548 LocalText 7900026 promises a single reward per
|
||||
// GameData 20261021182514 LocalText 7900026 promises a single reward per
|
||||
// board first clear; 7900084 requires every stage win; 7900122 resets run items.
|
||||
// IbStageEndResponse and RewardDBInfoBundle field numbers are from the current
|
||||
// extracted Proto.Net classes. This exercises the actual account transaction,
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
)
|
||||
|
||||
// CommonPacket.GetCharInfo(long) consults supporter caches before owned characters.
|
||||
// CharDBInfo/CostumeDBInfo/EquipDBInfo link by instance index, not design ID.
|
||||
func TestTwoAccountsKeepDistinctOwnedIdentitiesWhenBorrowingSameCharacter(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
type supporter struct{ character, costume, equipment uint64 }
|
||||
var supporters [2]supporter
|
||||
var snapshots [2]map[uint64]string
|
||||
owners := map[string]*playerInstance{}
|
||||
t.Cleanup(func() {
|
||||
for _, owner := range owners {
|
||||
closeNicknamePlayer(t, owner)
|
||||
}
|
||||
})
|
||||
closeOwner := func(account string) {
|
||||
closeNicknamePlayer(t, owners[account])
|
||||
delete(owners, account)
|
||||
}
|
||||
weaponIDs := make([]uint64, 0)
|
||||
for id, slot := range factory.design.equipmentSlots {
|
||||
if slot == 1 {
|
||||
weaponIDs = append(weaponIDs, id)
|
||||
}
|
||||
}
|
||||
slices.Sort(weaponIDs)
|
||||
if len(weaponIDs) == 0 {
|
||||
t.Fatal("selected GameData has no weapon")
|
||||
}
|
||||
// Current GameData CostumeTable 101 belongs to UniqueCharId 1; the selected
|
||||
// starter seed owns neither this costume nor its permanent character.
|
||||
const costumeID = 101
|
||||
design, found := factory.design.rewardCostumes.Character(costumeID)
|
||||
if !found {
|
||||
t.Fatal("selected GameData has no grantable costume", costumeID)
|
||||
}
|
||||
for i, account := range accounts {
|
||||
owner := openNicknamePlayer(t, factory, account)
|
||||
owners[account] = owner
|
||||
initial := inventoryIdentitySnapshot(t, owner)
|
||||
if i > 0 {
|
||||
assertInventoryIdentityDisjoint(t, snapshots[0], initial)
|
||||
}
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx, InstanceIDs: factory.instanceIDs()}
|
||||
grant, err := owner.assembly.collection.GrantCostumes(ctx, "same-character-award", []uint64{costumeID}, factory.design.rewardCostumes)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(grant.CharacterIndices) != 1 || len(grant.CostumeIndices) != 1 {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal("first costume acquisition did not create its character and costume")
|
||||
}
|
||||
character, found := owner.assembly.collection.FindCharacter(grant.CharacterIndices[0])
|
||||
if !found || character.ID != design.ID || character.CostumeID != costumeID || character.UseCostume != grant.CostumeIndices[0] {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal("acquired character does not reference its actual owned costume")
|
||||
}
|
||||
equipment, err := owner.assembly.ownedEquipment.GrantOnce(ctx, "same-weapon-award", weaponIDs[0])
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := append(append(appScalar(1, 1), appScalar(2, equipment.InvenIndex)...), appScalar(3, character.InvenIndex)...)
|
||||
if _, _, handled, err := owner.assembly.ownedEquipment.Handle(ctx, "/EquipUse", request); err != nil || !handled {
|
||||
_ = tx.Rollback()
|
||||
t.Fatalf("equip actual owned weapon: handled=%t error=%v", handled, err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
supporters[i] = supporter{character.InvenIndex, character.UseCostume, equipment.InvenIndex}
|
||||
snapshots[i] = inventoryIdentitySnapshot(t, owner)
|
||||
for index, identity := range initial {
|
||||
if snapshots[i][index] != identity {
|
||||
t.Fatalf("grant changed an existing starter identity: %d", index)
|
||||
}
|
||||
}
|
||||
closeOwner(account)
|
||||
}
|
||||
assertInventoryIdentityDisjoint(t, snapshots[0], snapshots[1])
|
||||
|
||||
// Recreate the allocator and application against the same SQLite account files.
|
||||
factory = &PlayerFactory{options: factory.options, seeds: factory.seeds, design: factory.design, profiles: factory.profiles}
|
||||
for i, account := range accounts {
|
||||
owner := openNicknamePlayer(t, factory, account)
|
||||
owners[account] = owner
|
||||
if !maps.Equal(snapshots[i], inventoryIdentitySnapshot(t, owner)) {
|
||||
t.Fatal("account reopen changed inventory identities or ownership links")
|
||||
}
|
||||
closeOwner(account)
|
||||
}
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
registry := newPlayerRegistry(factory, time.Minute)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
clients := []*friendHTTPClient{friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])}
|
||||
for i, client := range clients {
|
||||
fields := append(append(appScalar(2, 1), appScalar(3, supporters[i].character)...), appScalar(4, supporters[i].costume)...)
|
||||
client.send("/SupporterRegister", fields, 435, 0)
|
||||
drainFriendPublications(t, registry, shared, accounts[i])
|
||||
}
|
||||
borrower, lender := clients[0], clients[1]
|
||||
borrower.send("/FriendSend", appScalar(2, lender.owner), 205, 0)
|
||||
lender.send("/FriendAccept", appScalar(2, borrower.owner), 206, 0)
|
||||
borrower.send("/SupporterBattleInfo", appScalar(2, 1), 439, 0)
|
||||
borrowed := borrower.send("/SupporterBorrow", append(appScalar(2, lender.owner), appScalar(3, 1)...), 437, 0)
|
||||
bundles := appRows(borrowed, 3)
|
||||
if len(bundles) != 1 {
|
||||
t.Fatal("borrow omitted the native supporter bundle")
|
||||
}
|
||||
characters, costumes, equipment := appRows(bundles[0], 1), appRows(bundles[0], 2), appRows(bundles[0], 3)
|
||||
if len(characters) != 1 || appValue(characters[0], 1) != supporters[1].character || appValue(characters[0], 2) != design.ID || appValue(characters[0], 7) != supporters[1].costume {
|
||||
t.Fatal("borrowed character does not preserve lender ownership and costume references")
|
||||
}
|
||||
if len(costumes) != 1 || appValue(costumes[0], 1) != supporters[1].costume || appValue(costumes[0], 2) != costumeID || appValue(costumes[0], 4) != supporters[1].character {
|
||||
t.Fatal("borrowed costume does not point to lender's actual character")
|
||||
}
|
||||
if len(equipment) != 1 || appValue(equipment[0], 1) != supporters[1].equipment || appValue(equipment[0], 2) != supporters[1].character {
|
||||
t.Fatal("borrowed equipment does not point to lender's actual character")
|
||||
}
|
||||
for _, rows := range [][][]byte{characters, costumes, equipment} {
|
||||
for _, row := range rows {
|
||||
if _, own := snapshots[0][appValue(row, 1)]; own {
|
||||
t.Fatal("supporter cache would shadow borrower's owned inventory")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func inventoryIdentitySnapshot(t *testing.T, owner *playerInstance) map[uint64]string {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
identities := map[uint64]string{}
|
||||
add := func(index uint64, identity string) {
|
||||
t.Helper()
|
||||
if index == 0 {
|
||||
t.Fatal("owned instance has no identity", identity)
|
||||
}
|
||||
if previous, exists := identities[index]; exists {
|
||||
t.Fatalf("instance %d resolves to both %s and %s", index, previous, identity)
|
||||
}
|
||||
identities[index] = identity
|
||||
}
|
||||
for _, character := range owner.assembly.worldService.CharacterService().RawAll() {
|
||||
if !roster.IsStoryCharacter(character) && !roster.IsCharmCharacter(character) {
|
||||
add(character.InvenIndex, fmt.Sprintf("character:%d:costume:%d", character.ID, character.UseCostume))
|
||||
}
|
||||
}
|
||||
for _, costume := range owner.assembly.collection.Costumes() {
|
||||
add(costume.InvenIndex, fmt.Sprintf("costume:%d:character:%d", costume.ID, costume.UseChar))
|
||||
}
|
||||
for _, item := range owner.assembly.ownedItems.All(ctx) {
|
||||
if item.InvenIndex != 0 {
|
||||
add(item.InvenIndex, fmt.Sprintf("item:%d:%d", item.Type, item.ID))
|
||||
}
|
||||
}
|
||||
for _, equipment := range owner.assembly.ownedEquipment.All(ctx) {
|
||||
add(equipment.InvenIndex, fmt.Sprintf("equipment:%d:character:%d", equipment.ID, equipment.UseChar))
|
||||
}
|
||||
if len(identities) == 0 {
|
||||
t.Fatal("new account has no inventory")
|
||||
}
|
||||
return identities
|
||||
}
|
||||
|
||||
func assertInventoryIdentityDisjoint(t *testing.T, left, right map[uint64]string) {
|
||||
t.Helper()
|
||||
for id, leftIdentity := range left {
|
||||
if rightIdentity, exists := right[id]; exists {
|
||||
t.Fatalf("accounts share instance %d: %s and %s", id, leftIdentity, rightIdentity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ func inventorySetup(t *testing.T, g *puzzleGameplay, fn func(command.Context, *p
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
fn(command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "setup"}, State: tx}, g.owner.assembly)
|
||||
fn(command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "setup"}, State: tx, InstanceIDs: g.factory.instanceIDs()}, g.owner.assembly)
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
)
|
||||
|
||||
func missionGrant(t *testing.T, g *missionGameplay, rewards ...gamedata.Reward) {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
if _, err := g.owner.assembly.eventEconomy.Apply(ctx, "mission-condition:"+t.Name(), nil, rewards); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// persistedEventMissionValue reads the saved event mission without asking the
|
||||
// service, whose own reconciliation would hide whether login did the work.
|
||||
func persistedEventMissionValue(t *testing.T, g *missionGameplay, taskID uint64) uint64 {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
raw, err := g.owner.assembly.gameplayStore.Load(tx, "eventtasks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw == nil {
|
||||
return 0
|
||||
}
|
||||
var state struct {
|
||||
Missions map[string]struct{ Value uint64 }
|
||||
}
|
||||
if err := json.Unmarshal(raw, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
suffix := "/" + strconv.FormatUint(taskID, 10)
|
||||
var matches []uint64
|
||||
for key, mission := range state.Missions {
|
||||
if strings.HasSuffix(key, suffix) {
|
||||
matches = append(matches, mission.Value)
|
||||
}
|
||||
}
|
||||
if len(matches) > 1 {
|
||||
t.Fatalf("mission %d appears under %d schedules", taskID, len(matches))
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
return 0
|
||||
}
|
||||
return matches[0]
|
||||
}
|
||||
|
||||
// persistedRegularMissionValue reads a zero-valued regular mission, which
|
||||
// MissionInfo omits until its progress is non-zero.
|
||||
func persistedRegularMissionValue(t *testing.T, g *missionGameplay, groupType, group, id uint64) uint64 {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
raw, err := g.owner.assembly.scope.Load(tx, "missions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw == nil {
|
||||
return 0
|
||||
}
|
||||
var state struct{ Progress map[string]uint64 }
|
||||
if err := json.Unmarshal(raw, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return state.Progress[fmt.Sprintf("%d/%d/%d", groupType, group, id)]
|
||||
}
|
||||
|
||||
// guideTask finds a step-one guide mission without querying EventMissionInfo,
|
||||
// which would reconcile the very progress under test.
|
||||
func guideTask(t *testing.T, g *missionGameplay, groups map[uint64]bool, condition, subtype uint64) uint64 {
|
||||
t.Helper()
|
||||
for _, task := range g.factory.design.eventTasksDesign.Missions {
|
||||
if groups[task.Group] && task.Type == condition && task.SubType == subtype {
|
||||
return task.ID
|
||||
}
|
||||
}
|
||||
t.Fatalf("no guide step mission with condition %d subtype %d", condition, subtype)
|
||||
return 0
|
||||
}
|
||||
|
||||
// setPermanentCharacterLevel rewrites one saved permanent character, emulating
|
||||
// progress that predates the guide step.
|
||||
func setPermanentCharacterLevel(t *testing.T, g *missionGameplay, level uint64) {
|
||||
t.Helper()
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
var target roster.Character
|
||||
for _, character := range p.worldService.CharacterService().RawAll() {
|
||||
if !roster.IsStoryCharacter(character) && !roster.IsCharmCharacter(character) {
|
||||
target = character
|
||||
break
|
||||
}
|
||||
}
|
||||
if target.InvenIndex == 0 {
|
||||
t.Fatal("fixture has no permanent character")
|
||||
}
|
||||
key := strconv.FormatUint(target.InvenIndex, 10)
|
||||
raw, found, err := p.scope.LoadEntry(ctx.State, "characters", "characters", key)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("character entry %s: found=%v err=%v", key, found, err)
|
||||
}
|
||||
if err := json.Unmarshal(raw, &target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target.Level = level
|
||||
payload, err := json.Marshal(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.scope.PutEntry(ctx.State, "characters", "characters", key, payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
}
|
||||
|
||||
// MissionTable 303/3035 is guide step McCharTargetLevelUp: "reach character
|
||||
// level 20 or above". The level boundary must include 20, and the saved value
|
||||
// stays zero until login reconciles it.
|
||||
func TestGuidePassCharacterLevelMissionBackfillsAtLogin(t *testing.T) {
|
||||
for _, test := range []struct{ level, complete uint64 }{{1, 0}, {19, 0}, {20, 1}, {21, 1}} {
|
||||
t.Run(fmt.Sprintf("level%d", test.level), func(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
groups, _ := guideStepOne(t, g)
|
||||
id := guideTask(t, g, groups, 207, 20)
|
||||
if test.level > 1 {
|
||||
setPermanentCharacterLevel(t, g, test.level)
|
||||
}
|
||||
if got := persistedEventMissionValue(t, g, id); got != 0 {
|
||||
t.Fatalf("mission advanced before login: %d", got)
|
||||
}
|
||||
g.call("/LoginUser", nil)
|
||||
want := missionTarget(t, g, id) * test.complete
|
||||
if got := persistedEventMissionValue(t, g, id); got != want {
|
||||
t.Fatalf("character level mission value=%d, want %d", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// MissionTable 303/3039 is guide step McPlatformConnectOrLogin. Every session
|
||||
// belongs to an authenticated account, so login completes it.
|
||||
func TestGuidePassPlatformLoginMissionCompletesAtLogin(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
groups, _ := guideStepOne(t, g)
|
||||
id := guideTask(t, g, groups, 231, 0)
|
||||
if got := persistedEventMissionValue(t, g, id); got != 0 {
|
||||
t.Fatalf("platform login mission started at %d, want 0", got)
|
||||
}
|
||||
g.call("/LoginUser", nil)
|
||||
if got, want := persistedEventMissionValue(t, g, id), missionTarget(t, g, id); got != want {
|
||||
t.Fatalf("platform login mission value=%d, want %d", got, want)
|
||||
}
|
||||
row, _ := guideConditionMission(t, g, groups, 231, 0)
|
||||
if got, want := appValue(row, 4), missionTarget(t, g, id); got != want {
|
||||
t.Fatalf("platform login mission served value=%d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A roguelike battle reports McPackBattle with the GameData roguelike pack and
|
||||
// the ROGUE_LIKE battle mode, which completes the generic daily pack-battle
|
||||
// mission.
|
||||
func TestRogueLikeBattleReportsPackAndMode(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
// GameData mission 1/112 is inside its 1999-01-01..2024-05-13 window.
|
||||
g.now = time.Date(2024, time.May, 1, 12, 0, 0, 0, time.UTC)
|
||||
event := g.owner.assembly.rogueLikeBattleEvent()
|
||||
if event.Type != conditions.PackBattle || event.Sub != g.factory.design.roguelike.Pack || event.Param != battleModeRogueLike || event.Count != 1 {
|
||||
t.Fatalf("roguelike battle event = %+v", event)
|
||||
}
|
||||
if battleModeRogueLike != 21 {
|
||||
t.Fatalf("roguelike battle mode = %d, want ROGUE_LIKE 21", battleModeRogueLike)
|
||||
}
|
||||
g.call("/LoginUser", nil)
|
||||
if got := persistedRegularMissionValue(t, g, 0, 1, 112); got != 0 {
|
||||
t.Fatalf("pack battle mission started at %d, want 0", got)
|
||||
}
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if err := p.recordRogueLikeBattle(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
if got := persistedRegularMissionValue(t, g, 0, 1, 112); got != 1 {
|
||||
t.Fatalf("pack battle mission value=%d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// MissionTable 2/208 is McTalentSkillUse with SubType 9
|
||||
// (Define_TalentSkillType TS_EQUIPMENT_MAKING): one successful equipment
|
||||
// making request completes it.
|
||||
func TestEquipmentMakingCompletesTalentSkillMission(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
g.call("/LoginUser", nil)
|
||||
var character uint64
|
||||
var materials []byte
|
||||
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if _, err := p.collection.GrantCostumes(ctx, "talent-skill-mission", []uint64{1401}, p.design.regularGacha); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range p.worldService.CharacterService().EquipmentCharacters() {
|
||||
if _, ok := p.design.equipmentCraft.CharTalent[c.ID]; ok {
|
||||
character = c.InvenIndex
|
||||
break
|
||||
}
|
||||
}
|
||||
if character == 0 {
|
||||
t.Fatal("fixture needs a crafting character")
|
||||
}
|
||||
rewards := []gamedata.BattleReward{{Type: 8, ID: 204, Count: 50}, {Type: 8, ID: 201, Count: 50}}
|
||||
if _, err := p.ownedItems.GrantOnce(ctx, "talent-skill-materials", rewards); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.wallet.ExchangeOnce(ctx, "talent-skill-wallet", nil, []gamedata.Reward{{Type: 4, Count: 1000000}, {Type: 12, Count: 100}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range []uint64{204, 201} {
|
||||
items, err := p.ownedItems.SelectMutable(ctx, 8, id, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, item := range items {
|
||||
materials = append(materials, appMessage(4, assets.ItemWire(item))...)
|
||||
}
|
||||
}
|
||||
})
|
||||
g.reopen()
|
||||
if got := persistedRegularMissionValue(t, g, 1, 2, 208); got != 0 {
|
||||
t.Fatalf("talent skill mission started at %d, want 0", got)
|
||||
}
|
||||
request := append(appScalar(2, character), appScalar(3, 1)...)
|
||||
request = append(request, materials...)
|
||||
request = append(request, appScalar(5, 0)...)
|
||||
request = append(request, appScalar(7, 1)...)
|
||||
request = append(request, appScalar(8, 3)...)
|
||||
g.call("/EquipFromMakingToUpgrade", request)
|
||||
if got := persistedRegularMissionValue(t, g, 1, 2, 208); got != 1 {
|
||||
t.Fatalf("talent skill mission value=%d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// MissionTable 1/110 is McSamGroupIdMissionUpdateCompleteCount (SubType 0):
|
||||
// completing any other daily mission in group 1 completes it, while a weekly
|
||||
// completion must not count.
|
||||
func TestSameGroupDailyMissionCountsCompletedDailyMissions(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
g.call("/LoginUser", nil)
|
||||
g.assertMission(0, 1, 101, 1, false)
|
||||
g.assertMission(0, 1, 110, 1, false)
|
||||
g.assertMission(1, 2, 210, 2, false)
|
||||
}
|
||||
|
||||
// MissionTable 1/111 and 302/3029 are McgachaBuy: one regular draw completes
|
||||
// both the daily mission and the guide step, and further draws do not exceed
|
||||
// their targets.
|
||||
func TestGachaMissionsProgressFromOneDraw(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
groups, _ := guideStepOne(t, g)
|
||||
row, guideID := guideConditionMission(t, g, groups, 9, 0)
|
||||
if row == nil {
|
||||
t.Fatal("guide gacha mission missing from EventMissionInfo")
|
||||
}
|
||||
if got := appValue(row, 4); got != 0 {
|
||||
t.Fatalf("guide gacha mission started at %d, want 0", got)
|
||||
}
|
||||
g.call("/LoginUser", nil)
|
||||
if got := persistedRegularMissionValue(t, g, 0, 1, 111); got != 0 {
|
||||
t.Fatalf("daily gacha mission started at %d, want 0", got)
|
||||
}
|
||||
// Pick a plain single draw paid with free jewelry, not a step-up, limited,
|
||||
// selection or first-gacha group, so two identical draws stay valid.
|
||||
catalog := g.factory.design.regularGacha
|
||||
var groupID, gachaID, price uint64
|
||||
for _, group := range catalog.Groups() {
|
||||
design, found := catalog.Gacha(group.OneTimeGachaID)
|
||||
if !found || design.Count != 1 || design.PriceType != 3 || design.Price == 0 {
|
||||
continue
|
||||
}
|
||||
if group.BuyLimitCount != 0 || group.SelectCount != 0 || group.GachaSubType != 0 {
|
||||
continue
|
||||
}
|
||||
if _, stepUp := catalog.StepForGacha(group.OneTimeGachaID); stepUp {
|
||||
continue
|
||||
}
|
||||
if g.factory.design.firstGacha != nil && g.factory.design.firstGacha.GachaID == group.OneTimeGachaID {
|
||||
continue
|
||||
}
|
||||
groupID, gachaID, price = group.ID, group.OneTimeGachaID, design.Price
|
||||
break
|
||||
}
|
||||
if groupID == 0 {
|
||||
t.Fatal("GameData has no single-draw gacha paid with free jewelry")
|
||||
}
|
||||
missionGrant(t, g, gamedata.Reward{Type: 3, ID: 0, Count: price * 2})
|
||||
g.call("/GachaBuy", append(appScalar(2, gachaID), appScalar(3, 1)...))
|
||||
g.assertMission(0, 1, 111, 1, false)
|
||||
row, _ = guideConditionMission(t, g, groups, 9, 0)
|
||||
if got, want := appValue(row, 4), missionTarget(t, g, guideID); got != want {
|
||||
t.Fatalf("guide gacha mission value=%d, want %d", got, want)
|
||||
}
|
||||
g.call("/GachaBuy", append(appScalar(2, gachaID), appScalar(3, 1)...))
|
||||
g.assertMission(0, 1, 111, 1, false)
|
||||
row, _ = guideConditionMission(t, g, groups, 9, 0)
|
||||
if got, want := appValue(row, 4), missionTarget(t, g, guideID); got != want {
|
||||
t.Fatalf("second draw inflated guide gacha mission to %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
@@ -111,11 +112,15 @@ func (g *missionGameplay) itemCount(typ, id uint64) uint64 {
|
||||
func (g *missionGameplay) assertMission(groupType, group, id, value uint64, claimed bool) {
|
||||
g.t.Helper()
|
||||
var row []byte
|
||||
found := false
|
||||
for _, candidate := range appRows(g.call("/MissionInfo", nil), 1) {
|
||||
if appValue(candidate, 1) == group && appValue(candidate, 2) == id && appValue(candidate, 3) == groupType {
|
||||
row = candidate
|
||||
row, found = candidate, true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
g.t.Fatalf("mission %d/%d/%d missing from MissionInfo", groupType, group, id)
|
||||
}
|
||||
if appValue(row, 4) != value || (appValue(row, 5) == 1) != claimed {
|
||||
g.t.Fatalf("mission %d/%d/%d: value=%d claimed=%v, want value=%d claimed=%v", groupType, group, id, appValue(row, 4), appValue(row, 5) == 1, value, claimed)
|
||||
}
|
||||
@@ -287,7 +292,7 @@ func TestMissionExpiredRowCannotReceiveCurrentGameplayEvents(t *testing.T) {
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
if err := g.owner.assembly.missionService.RecordEvent(ctx, 3, 0, 1, g.owner.assembly.worldService.MissionsUnlocked); err != nil {
|
||||
if err := g.owner.assembly.missionService.RecordEvent(ctx, conditions.Event{Type: 3, Count: 1}, g.owner.assembly.worldService.MissionsUnlocked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
|
||||
@@ -161,7 +161,7 @@ func (s *monsterHuntScenario) command(t *testing.T, action func(command.Context)
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
response, err := action(command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "hunt-client"}, State: tx})
|
||||
response, err := action(command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "hunt-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ func seedNicknameTickets(t *testing.T, owner *playerInstance, count uint64) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: owner.accountID}}
|
||||
ctx := command.Context{State: tx, InstanceIDs: owner.factory.instanceIDs(), Identity: command.Identity{AccountID: owner.accountID}}
|
||||
if _, err = owner.assembly.ownedItems.GrantOnce(ctx, "nickname-ticket-fixture", []gamedata.BattleReward{{Type: 14, ID: 1, Count: count}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ func (p *playerAssembly) assets(ctx command.Context) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("server starting chapter policy: %w", err)
|
||||
}
|
||||
if err := p.seedInstances(ctx); err != nil {
|
||||
return fmt.Errorf("initialize account instance identities: %w", err)
|
||||
}
|
||||
p.progressState, err = progress.OpenStore(ctx, p.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -39,12 +42,14 @@ func (p *playerAssembly) assets(ctx command.Context) error {
|
||||
if err := p.ownedItems.AttachItemStacks(p.design.itemStacks); err != nil {
|
||||
return err
|
||||
}
|
||||
p.ownedItems.AttachPrestigeIllustrations(p.design.prestigeCatalog.Illustrations)
|
||||
if p.initializeAccount {
|
||||
if err := p.ownedItems.InitializeItems(ctx, p.starter.OwnedItems); err != nil {
|
||||
return fmt.Errorf("initialize owned item seed: %w", err)
|
||||
}
|
||||
}
|
||||
if err := p.ownedItems.AttachPrestigeIllustrations(ctx, p.design.prestigeCatalog.Illustrations); err != nil {
|
||||
return fmt.Errorf("attach prestige illustration instances: %w", err)
|
||||
}
|
||||
p.recipeService, err = assets.NewRecipeService(p.design.recipeDesign, p.starter.CookingRecipes, p.ownedItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load learned recipes: %w", err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
)
|
||||
@@ -21,6 +22,13 @@ func (p *playerAssembly) AvatarItems(ctx command.Context) []assets.Item { return
|
||||
func (p *playerAssembly) AvatarCurrency(ctx command.Context) assets.Currency {
|
||||
return p.wallet.Snapshot(ctx)
|
||||
}
|
||||
func (p *playerAssembly) AvatarPriceBalance(ctx command.Context, price gamedata.Reward) (uint64, error) {
|
||||
if field, found := events.AdditionalCurrencyFields[price.Type]; found && price.ID == 0 {
|
||||
balances, err := p.eventEconomy.AdditionalCurrencies(ctx)
|
||||
return balances[field], err
|
||||
}
|
||||
return 0, fmt.Errorf("avatar: unsupported initial selection currency %d/%d", price.Type, price.ID)
|
||||
}
|
||||
func (p *playerAssembly) AvatarUnlocked(ctx command.Context, product gamedata.AvatarProduct) (bool, error) {
|
||||
if product.UnlockValue == 0 {
|
||||
return true, nil
|
||||
|
||||
@@ -9,6 +9,9 @@ import (
|
||||
)
|
||||
|
||||
func (p *playerAssembly) prepareBattle(ctx command.Context, result battle.Completion) error {
|
||||
if err := p.recordBattleStart(ctx, result); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(result.Deck) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -22,6 +25,9 @@ func (p *playerAssembly) prepareBattle(ctx command.Context, result battle.Comple
|
||||
}
|
||||
|
||||
func (p *playerAssembly) completeBattle(ctx command.Context, result battle.Completion) ([]byte, error) {
|
||||
if err := p.recordBattleEnd(ctx, result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
partners, err := p.rosterProgressService.ApplyBattlePartners(ctx, result.Identity, result.Participants, result.Win)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -34,6 +40,9 @@ func (p *playerAssembly) completeBattle(ctx command.Context, result battle.Compl
|
||||
}
|
||||
|
||||
func (p *playerAssembly) completePVP(ctx command.Context, mode pvp.Mode, identity string, win bool, enteredDeck [][]byte) ([]byte, error) {
|
||||
if err := p.recordPVPEnd(ctx, mode, win); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mode != pvp.Mirror {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -92,8 +92,8 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load event tasks state: %w", err)
|
||||
}
|
||||
if err := p.mailService.AttachAttendanceRewardEconomy(ctx, p.eventEconomy); err != nil {
|
||||
return fmt.Errorf("attach attendance mail rewards: %w", err)
|
||||
if err := p.mailService.AttachAttachmentRewardEconomy(ctx, p.eventEconomy); err != nil {
|
||||
return fmt.Errorf("attach mail attachment rewards: %w", err)
|
||||
}
|
||||
p.eventTasksService.AttachAttendanceMail(p.mailService)
|
||||
newbieStep, _, err := wire.Varint(p.login.UserInfo, 39)
|
||||
@@ -135,6 +135,9 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
|
||||
}
|
||||
p.loginPasses.SetClock(time.Now, p.design.eventAPReset.ResetSeconds-9*3600)
|
||||
p.eventTasksService.AttachUnlockResolver(p.worldService.MissionsUnlocked)
|
||||
p.eventTasksService.AttachProgress(p.recordMission)
|
||||
p.eventTasksService.AttachAccountState(p.missionAccountState)
|
||||
p.ownedEquipment.AttachMissionProgress(p.recordMission, func(id uint64) uint64 { return p.design.achievementGrades.Equipment[id] })
|
||||
if err = p.missionService.AttachEventHandler(ctx, p.eventTasksService); err != nil {
|
||||
return fmt.Errorf("attach mission event handler: %w", err)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"bd2server/internal/server/domain/events/tasks"
|
||||
"bd2server/internal/server/domain/fishing"
|
||||
"bd2server/internal/server/domain/progression/achievements"
|
||||
"bd2server/internal/server/domain/progression/missions"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
loginprotocol "bd2server/internal/server/protocol/login"
|
||||
"fmt"
|
||||
@@ -64,6 +64,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load fishing state: %w", err)
|
||||
}
|
||||
p.fishingService.AttachProgress(p.recordMission)
|
||||
if err := p.login.AttachFishing(func() loginprotocol.FishingState {
|
||||
state := p.fishingService.Profile()
|
||||
return loginprotocol.FishingState{AP: state.MultiAP, FishSlots: state.FishSlots, RodSlots: state.RodSlots, ItemSlots: state.ItemSlots}
|
||||
@@ -111,12 +112,8 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
p.eventActionsService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
|
||||
})
|
||||
p.eventPlayService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
|
||||
})
|
||||
p.eventActionsService.AttachProgress(p.recordMission)
|
||||
p.eventPlayService.AttachProgress(p.recordMission)
|
||||
p.eventPlayService.AttachRhythmResult(p.eventTasksService.RecordRhythmResult)
|
||||
p.eventTasksService.AttachAssociatedMissionGroup(func(schedule events.Schedule) uint64 {
|
||||
if group := p.eventActionsService.AssociatedMissionGroup(schedule); group != 0 {
|
||||
@@ -131,6 +128,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
p.battleService.AttachEventBattle(p.eventActionsService)
|
||||
p.battleService.AttachCurrentDifficulty(p.worldService.CurrentQuestDifficulty)
|
||||
p.battleService.AttachQuestBattleValidation(p.worldService.ValidateQuestBattle)
|
||||
p.worldService.AttachQuestVictory(p.battleService.HasWonQuest)
|
||||
p.battleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) {
|
||||
return p.eventEconomy.Apply(ctx, identity, nil, rewards)
|
||||
})
|
||||
@@ -186,7 +184,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return err
|
||||
}
|
||||
p.battleService.AttachMonsterWinMission(func(ctx command.Context) error {
|
||||
return p.missionService.CompleteSingleTargetEvent(ctx, missions.ConditionMonsterKill, p.worldService.MissionsUnlocked)
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.MonsterKill, Count: 1})
|
||||
})
|
||||
p.battleService.AttachPictorialBuffs(func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) {
|
||||
_, buffs, err := p.pictorialService.Snapshot(ctx)
|
||||
@@ -200,8 +198,10 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return fmt.Errorf("attach achievement completion validation: %w", err)
|
||||
}
|
||||
p.commissionService.CompleteAchievement = func(ctx command.Context, identity string) error {
|
||||
_, err := p.achievementCounters.RecordEvent(ctx, identity, 17, 0, 1)
|
||||
return err
|
||||
if _, err := p.achievementCounters.RecordEvent(ctx, identity, 17, 0, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.TodayQuestClear, Count: 1})
|
||||
}
|
||||
if err := p.login.AttachAchievementExperience(p.missionService); err != nil {
|
||||
return fmt.Errorf("attach persisted achievement experience: %w", err)
|
||||
@@ -215,11 +215,18 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return fmt.Errorf("initialize achievement gameplay observer: %w", err)
|
||||
}
|
||||
p.eventTasksService.AttachInventoryProvider(&eventtasks.InventoryProjection{Items: p.ownedItems, Equipment: p.ownedEquipment, Costumes: p.collection, StateVersion: p.stateRepository.ObservationVersion})
|
||||
p.eventTasksService.AttachGachaHistory(p.collection.GachaHistory)
|
||||
p.eventTasksService.AttachAchievementLevelReward(p.missionService.LevelRewardCount)
|
||||
p.worldService.AttachSkyWayProgress(p.eventTasksService.RecordSkyWayClear, func(ctx command.Context, group uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, 227, group, 1, p.worldService.MissionsUnlocked)
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.SkywayGroupBattle, Sub: group, Count: 1})
|
||||
})
|
||||
p.worldService.AttachMissionProgress(p.recordMission)
|
||||
p.eventEconomy.AttachProgress(p.recordMission)
|
||||
p.huntingService.AttachAPSpent(func(ctx command.Context, cost uint64) error {
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.ItemCurrencyUse, Sub: 21, Count: cost}) // EElementType FreeHuntingAP
|
||||
})
|
||||
p.huntingService.AttachDispatchProgress(func(ctx command.Context, count uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, 23, 0, count, p.worldService.MissionsUnlocked)
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.HuntDispatch, Count: count})
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
}
|
||||
}()
|
||||
|
||||
identity := command.Context{Identity: request.Identity, Cancellation: request.Cancellation, State: tx}
|
||||
identity := command.Context{Identity: request.Identity, Cancellation: request.Cancellation, State: tx, InstanceIDs: p.factory.instanceIDs()}
|
||||
published := false
|
||||
var chatPolicyPayload []byte
|
||||
identity.Emit = func(event command.Event) error {
|
||||
@@ -346,6 +346,15 @@ func (p *playerAssembly) beginLogin(ctx command.Context) error {
|
||||
if err := p.eventTasksService.ReconcileRhythmResults(ctx, p.eventPlayService.CompletedRhythmResults()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.eventTasksService.ReconcileAccountState(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.cafeteriaService.ReconcileIntroduction(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.worldService.ClaimOpenFieldPacks(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.missionService.RecordLogin(ctx, p.worldService.MissionsUnlocked)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/util"
|
||||
"bd2server/internal/server/domain/battle"
|
||||
"bd2server/internal/server/domain/battle/castle"
|
||||
"bd2server/internal/server/domain/battle/hunting"
|
||||
@@ -41,6 +42,7 @@ import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/account"
|
||||
identitystore "bd2server/internal/server/storage/identity"
|
||||
"bd2server/internal/server/storage/instanceid"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"context"
|
||||
"errors"
|
||||
@@ -48,23 +50,33 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PlayerFactory struct {
|
||||
roomResults *roomResults
|
||||
shared *sharedRuntime
|
||||
pvpSource pvp.Source
|
||||
wakeOutbox func(string)
|
||||
options *configuration
|
||||
design *designCatalog
|
||||
seeds *seedCatalog
|
||||
profiles interface {
|
||||
instanceOnce sync.Once
|
||||
instanceSource util.InstanceIDSource
|
||||
roomResults *roomResults
|
||||
shared *sharedRuntime
|
||||
pvpSource pvp.Source
|
||||
wakeOutbox func(string)
|
||||
options *configuration
|
||||
design *designCatalog
|
||||
seeds *seedCatalog
|
||||
profiles interface {
|
||||
GameIdentity(context.Context, string) (identitystore.GameProfile, error)
|
||||
RecordGameLogin(context.Context, string, time.Time) error
|
||||
}
|
||||
}
|
||||
|
||||
func (f *PlayerFactory) instanceIDs() util.InstanceIDSource {
|
||||
f.instanceOnce.Do(func() {
|
||||
f.instanceSource = instanceid.New(filepath.Join(f.options.stateDirectory, "instance-ids.db"))
|
||||
})
|
||||
return f.instanceSource
|
||||
}
|
||||
|
||||
type playerAssembly struct {
|
||||
cafeteriaService *cafeteria.Service
|
||||
datingService *dating.Service
|
||||
@@ -236,7 +248,7 @@ func (f *PlayerFactory) assemble(ctx context.Context, accountID string, reposito
|
||||
}
|
||||
}()
|
||||
|
||||
identity := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "startup", RequestID: "initialize"}, Cancellation: ctx, State: startupTransaction}
|
||||
identity := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "startup", RequestID: "initialize"}, Cancellation: ctx, State: startupTransaction, InstanceIDs: f.instanceIDs()}
|
||||
for _, assemble := range []func(command.Context) error{p.assets, p.worldRoster, p.gameplay, p.commerce, p.events, p.optionalGameplay, p.openIB, p.rogueLike, p.session} {
|
||||
if err := assemble(identity); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events/calendar"
|
||||
"bd2server/internal/server/domain/identity"
|
||||
"bd2server/internal/server/domain/mail"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
@@ -208,6 +209,27 @@ func appItemTotals(body []byte) map[[2]uint64]uint64 {
|
||||
}
|
||||
func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
// The captured starter mailbox has fixed expirations; keep one resource
|
||||
// gift claimable so this isolation test does not become time-dependent.
|
||||
isResourceMail := func(entry *mail.MailDBInfo) bool {
|
||||
if len(entry.RewardTypes) == 0 {
|
||||
return false
|
||||
}
|
||||
for i, kind := range entry.RewardTypes {
|
||||
if kind != 8 || entry.RewardIDs[i] == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
now := uint64(time.Now().UnixMilli())
|
||||
for i := range factory.seeds.mailbox.Mails {
|
||||
entry := &factory.seeds.mailbox.Mails[i]
|
||||
if isResourceMail(entry) && entry.ExpiresAt <= now {
|
||||
entry.ExpiresAt = now + 24*60*60*1000
|
||||
break
|
||||
}
|
||||
}
|
||||
aID, bID := accounts[0], accounts[1]
|
||||
instances := map[string]*playerInstance{}
|
||||
runtimes := map[string]*player.Runtime{}
|
||||
@@ -231,13 +253,12 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T
|
||||
t.Fatal("assemble actual account", accountID, err)
|
||||
}
|
||||
instances[accountID] = instance
|
||||
// Establish one owned weapon as an explicit test grant before the actor is
|
||||
// exposed. Both players may legitimately use equal inventory numbers.
|
||||
// Establish one owned weapon as an explicit grant before exposing the actor.
|
||||
tx, err := instance.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "fixture", RequestID: "weapon"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "fixture", RequestID: "weapon"}, State: tx, InstanceIDs: factory.instanceIDs()}
|
||||
equipment, err := instance.assembly.ownedEquipment.GrantOnce(ctx, "test-owned-weapon", equipmentID)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
@@ -385,13 +406,7 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T
|
||||
var starterMail uint64
|
||||
expectedItems := map[[2]uint64]uint64{}
|
||||
for _, entry := range factory.seeds.mailbox.Mails {
|
||||
valid := len(entry.RewardTypes) > 0
|
||||
for i, kind := range entry.RewardTypes {
|
||||
if kind != 8 || entry.RewardIDs[i] == 0 {
|
||||
valid = false
|
||||
}
|
||||
}
|
||||
if valid && entry.ExpiresAt > uint64(time.Now().UnixMilli()) {
|
||||
if isResourceMail(&entry) && entry.ExpiresAt > now {
|
||||
starterMail = entry.MailID
|
||||
for i, kind := range entry.RewardTypes {
|
||||
expectedItems[[2]uint64{kind, entry.RewardIDs[i]}] += entry.RewardCounts[i]
|
||||
@@ -470,7 +485,7 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T
|
||||
}
|
||||
bEquipment := appRows(query(bID, "/EquipInfo", 21), 1)
|
||||
if len(bEquipment) != 1 || appValue(bEquipment[0], 2) != 0 {
|
||||
t.Fatal("A equipped B's equal-index weapon")
|
||||
t.Fatal("A equipped B's weapon")
|
||||
}
|
||||
aEquipment := appRows(query(aID, "/EquipInfo", 22), 1)
|
||||
if len(aEquipment) != 1 || appValue(aEquipment[0], 2) != characterIndex[aID] {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// missionActionObserver counts mission conditions whose action is one
|
||||
// successful request with no richer domain event. It runs before the event
|
||||
// mission observer, so that observer's notification includes the progress.
|
||||
type missionActionObserver struct{ player *playerAssembly }
|
||||
|
||||
// missionActionPaths maps a request to the Define_MissionConditionType it
|
||||
// performs once.
|
||||
var missionActionPaths = map[string]uint64{
|
||||
"/CafeteriaCumulativeReward": conditions.CafeteriaCumulativeReward,
|
||||
"/MyRoomItemInfo": conditions.MyRoomVisit,
|
||||
"/MyRoomLike": conditions.MyRoomLike,
|
||||
"/ShopBuy": conditions.BuyItemInShop,
|
||||
"/SquareReward": conditions.SquareReward,
|
||||
"/MercenaryScout": conditions.CharScoutToTargetGrade,
|
||||
"/CharSpecialScoutBuy": conditions.CharScoutToTargetGrade,
|
||||
}
|
||||
|
||||
func (o missionActionObserver) BeforeDispatch(command.Context, string, []byte) error { return nil }
|
||||
|
||||
func (o missionActionObserver) AfterDispatch(ctx command.Context, path string, request, _ []byte) ([]byte, error) {
|
||||
condition, ok := missionActionPaths[path]
|
||||
if path == "/MyRoomUserInfo" {
|
||||
// Field 2 is the room owner; the account's own room is a visit.
|
||||
owner, err := o.player.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target, _, _ := wire.Varint(request, 2)
|
||||
condition, ok = conditions.MyRoomVisit, target == owner
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, o.player.recordMission(ctx, conditions.Event{Type: condition, Count: 1})
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle"
|
||||
"bd2server/internal/server/domain/battle/castle"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
)
|
||||
|
||||
// recordMission applies one authoritative occurrence to the regular missions
|
||||
// and, through their event handler, to the scheduled event missions.
|
||||
func (p *playerAssembly) recordMission(ctx command.Context, event conditions.Event) error {
|
||||
return p.missionService.RecordEvent(ctx, event, p.worldService.MissionsUnlocked)
|
||||
}
|
||||
|
||||
// missionAccountState derives the progress of conditions that describe
|
||||
// account state rather than an occurrence, so progress made before a mission
|
||||
// opened, or before the server recorded the action, still counts. Values are
|
||||
// raised only; the event mission service never lowers recorded progress.
|
||||
func (p *playerAssembly) missionAccountState(ctx command.Context, specs []conditions.Spec) ([]uint64, error) {
|
||||
values := make([]uint64, len(specs))
|
||||
var castleProgress *castle.MissionProgress
|
||||
loadCastle := func() (*castle.MissionProgress, error) {
|
||||
if castleProgress == nil {
|
||||
progress, err := p.castleService.MissionProgress(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
castleProgress = &progress
|
||||
}
|
||||
return castleProgress, nil
|
||||
}
|
||||
var bestRank *uint64
|
||||
for i, spec := range specs {
|
||||
switch spec.Type {
|
||||
case conditions.PlatformConnectOrLogin:
|
||||
// Every session belongs to an authenticated platform account, so
|
||||
// the account is always bound.
|
||||
values[i] = 1
|
||||
case conditions.PackQuestIDClear: // pack = SubType, quests = Params
|
||||
for _, quest := range spec.Params {
|
||||
if quest != 0 && p.worldService.MissionsUnlocked(ctx, spec.SubType, quest) {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
case conditions.CharTargetLevelUp:
|
||||
values[i] = p.countCharacters(spec, func(c roster.Character) uint64 { return c.Level })
|
||||
case conditions.CharTargetGradeUp:
|
||||
values[i] = p.countCharacters(spec, func(c roster.Character) uint64 { return p.design.achievementGrades.CharacterGrowth[c.ID] })
|
||||
case conditions.CostumePotentialNodeKind: // SubType = CostumeNodeTable NodeType
|
||||
for _, costume := range p.collection.Costumes() {
|
||||
for _, id := range costume.PotentialIDs {
|
||||
if node, ok := p.design.costumePotentialDesign.Nodes[costume.ID][id]; ok && node.NodeType == spec.SubType {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
}
|
||||
case conditions.PvpRankGoal: // SubType = MirrorRankTable ID; lower IDs rank higher
|
||||
if p.pvpService == nil {
|
||||
continue
|
||||
}
|
||||
if bestRank == nil {
|
||||
best, err := p.pvpService.BestMirrorRankID(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bestRank = &best
|
||||
}
|
||||
if *bestRank != 0 && *bestRank <= spec.SubType {
|
||||
values[i] = 1
|
||||
}
|
||||
case conditions.TalentSkillUpgrade: // SubType = talent class, Params = level
|
||||
for _, c := range p.permanentCharacters() {
|
||||
character, ok := p.design.talentUseDesign.Characters[c.ID]
|
||||
rule, known := p.design.talentUseDesign.Rules[[2]uint64{character.Group, c.TalentLevel}]
|
||||
if ok && known && rule.Class == spec.SubType && (conditions.AnyParam(spec.Params) || c.TalentLevel >= spec.Params[0]) {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
case conditions.OtherGroupMissionComplete: // SubType = regular GroupId
|
||||
values[i] = p.missionService.CompletedMissionCount(spec.SubType)
|
||||
case conditions.DatingEpisodeClear:
|
||||
if p.datingService != nil {
|
||||
values[i] = p.datingService.ClearedEpisodeGroups()
|
||||
}
|
||||
case conditions.CharImprintLevelUp:
|
||||
for _, awake := range p.collection.CharAwakeStates() {
|
||||
for _, level := range awake.ImprintLevels {
|
||||
values[i] += level
|
||||
}
|
||||
}
|
||||
case conditions.CharAwakeActive:
|
||||
for _, awake := range p.collection.CharAwakeStates() {
|
||||
if awake.IsAwake {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
case conditions.EvilCastleRageTowerClear, conditions.EvilCastleEnvyTowerClear, conditions.EvilCastleGreedTowerClear: // SubType = floor
|
||||
if p.castleService == nil {
|
||||
continue
|
||||
}
|
||||
progress, err := loadCastle()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Define_BattleModeType: 19 RAGE, 20 ENVY, 16 GREED.
|
||||
mode := map[uint64]uint64{conditions.EvilCastleRageTowerClear: 19, conditions.EvilCastleEnvyTowerClear: 20, conditions.EvilCastleGreedTowerClear: 16}[spec.Type]
|
||||
if progress.Towers[mode][spec.SubType] {
|
||||
values[i] = 1
|
||||
}
|
||||
case conditions.EvilCastleFloorBattle, conditions.EvilCastleFloorClear: // SubType = Pride floor
|
||||
if p.castleService == nil {
|
||||
continue
|
||||
}
|
||||
progress, err := loadCastle()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reached := progress.PrideCleared
|
||||
if spec.Type == conditions.EvilCastleFloorBattle {
|
||||
reached = progress.PrideFought
|
||||
}
|
||||
if reached[spec.SubType] {
|
||||
values[i] = 1
|
||||
}
|
||||
case conditions.TotalWarResultScore:
|
||||
if p.castleService == nil {
|
||||
continue
|
||||
}
|
||||
progress, err := loadCastle()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if spec.SubTypeReached(progress.TotalWarBest) {
|
||||
values[i] = 1
|
||||
}
|
||||
case conditions.EquipmentUpgradeToLevel:
|
||||
for _, equipment := range p.ownedEquipment.All(ctx) {
|
||||
if equipment.Level >= spec.SubType {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
case conditions.FishingBoatUpgrade: // SubType = boat level
|
||||
if p.fishingService != nil && p.fishingService.Profile().BoatLevel >= spec.SubType {
|
||||
values[i] = 1
|
||||
}
|
||||
case conditions.FriendshipTargetLevelUp: // SubType = friendship level
|
||||
for _, entry := range p.collection.FriendshipEntries() {
|
||||
if entry.State != nil && entry.State.Level >= spec.SubType {
|
||||
values[i]++
|
||||
}
|
||||
}
|
||||
case conditions.FriendshipCostumeLevelUp: // SubType = costume; value = its friendship level
|
||||
if entry, ok := p.collection.FriendshipEntries()["costume:"+strconv.FormatUint(spec.SubType, 10)]; ok && entry.State != nil {
|
||||
values[i] = entry.State.Level
|
||||
}
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// permanentCharacters excludes temporary charm and story characters, which
|
||||
// do not belong to the account roster.
|
||||
func (p *playerAssembly) permanentCharacters() []roster.Character {
|
||||
var out []roster.Character
|
||||
for _, c := range p.worldService.CharacterService().RawAll() {
|
||||
if !roster.IsCharmCharacter(c) && !roster.IsStoryCharacter(c) {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// countCharacters counts the permanent characters whose value reached the
|
||||
// SubType and whose UniqueCharId is listed in Params. Reaching a higher level
|
||||
// or grade includes the lower one the mission names.
|
||||
func (p *playerAssembly) countCharacters(spec conditions.Spec, value func(roster.Character) uint64) uint64 {
|
||||
var count uint64
|
||||
for _, c := range p.permanentCharacters() {
|
||||
if value(c) >= spec.SubType && spec.ParamAccepts(p.design.costumePotentialDesign.CharacterUnique[c.ID]) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Define_BattleModeType values the battle mission conditions name.
|
||||
const (
|
||||
battleModeHuntingGround uint64 = 5 // HUNTING_GROUND
|
||||
battleModePVP uint64 = 6 // PVP
|
||||
battleModeMonsterHunt uint64 = 8 // MONSTER_HUNT
|
||||
battleModeMonsterHuntPractice uint64 = 24 // MONSTER_HUNT_PRACTICE
|
||||
battleModeRogueLike uint64 = 21 // ROGUE_LIKE
|
||||
packTypePVP uint64 = 3 // Define_PackType PVP
|
||||
)
|
||||
|
||||
// recordBattleStart counts the first round of an encounter.
|
||||
func (p *playerAssembly) recordBattleStart(ctx command.Context, result battle.Completion) error {
|
||||
mode := result.Context.BattleMode
|
||||
events := []conditions.Event{{Type: conditions.BattleModeStartTry, Sub: mode, Count: 1}}
|
||||
seen := map[uint64]bool{}
|
||||
for _, index := range result.Participants {
|
||||
character, owned := p.worldService.CharacterService().Find(ctx, index)
|
||||
unique := p.design.costumePotentialDesign.CharacterUnique[character.ID]
|
||||
if owned && unique != 0 && !seen[unique] {
|
||||
seen[unique] = true
|
||||
events = append(events, conditions.Event{Type: conditions.BattleStartWithUniqueChar, Sub: unique, Count: 1})
|
||||
}
|
||||
}
|
||||
if mode == battleModeMonsterHunt || mode == battleModeMonsterHuntPractice {
|
||||
events = append(events, conditions.Event{Type: conditions.MonsterHuntBattleWithTraining, Count: 1})
|
||||
}
|
||||
if mode == battleModeMonsterHunt {
|
||||
events = append(events, conditions.Event{Type: conditions.MonsterHuntBattle, Count: 1})
|
||||
}
|
||||
return p.recordMissions(ctx, events)
|
||||
}
|
||||
|
||||
// recordBattleEnd counts a settled encounter. McPackBattle names the pack as
|
||||
// SubType and the battle mode as its param.
|
||||
func (p *playerAssembly) recordBattleEnd(ctx command.Context, result battle.Completion) error {
|
||||
mode := result.Context.BattleMode
|
||||
events := []conditions.Event{{Type: conditions.PackBattle, Sub: result.Context.PackID, Param: mode, Count: 1}}
|
||||
if mode == battleModeHuntingGround || gamedata.IsSkyWayMode(mode) {
|
||||
events = append(events, conditions.Event{Type: conditions.HuntingBattle, Count: 1})
|
||||
}
|
||||
if mode == battleModeMonsterHunt && result.Win {
|
||||
events = append(events, conditions.Event{Type: conditions.MonsterHuntWin, Count: 1})
|
||||
}
|
||||
return p.recordMissions(ctx, events)
|
||||
}
|
||||
|
||||
// recordPVPEnd counts a settled Mirror battle in the PVP pack, and a
|
||||
// Colosseum victory.
|
||||
func (p *playerAssembly) recordPVPEnd(ctx command.Context, mode pvp.Mode, win bool) error {
|
||||
if mode == pvp.Colosseum {
|
||||
if !win {
|
||||
return nil
|
||||
}
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.ColosseumBattleWin, Count: 1})
|
||||
}
|
||||
for id, pack := range p.design.world.FieldPacks {
|
||||
if pack.Type == packTypePVP {
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.PackBattle, Sub: uint64(id), Param: battleModePVP, Count: 1})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) recordMissions(ctx command.Context, events []conditions.Event) error {
|
||||
for _, event := range events {
|
||||
if err := p.recordMission(ctx, event); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
@@ -41,6 +42,14 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
|
||||
}
|
||||
p.datingService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
|
||||
p.cafeteriaService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
|
||||
p.cafeteriaService.AttachDatingTicket(p.design.contentOpeningDesign.Dating.TicketID, func(ctx command.Context, ticket uint64) bool {
|
||||
for _, item := range p.ownedItems.All(ctx) {
|
||||
if item.Type == 19 && item.ID == ticket && item.Count > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
p.cafeteriaService.AttachOwnedCostumes(func() []uint64 {
|
||||
var ids []uint64
|
||||
for _, costume := range p.collection.Costumes() {
|
||||
@@ -49,6 +58,7 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
|
||||
return ids
|
||||
})
|
||||
p.cafeteriaService.AttachDatingHasEpisode(p.datingService.HasEpisode)
|
||||
p.worldService.AttachFieldPackEconomy(p.eventEconomy)
|
||||
p.datingService.AttachFirstMeeting(p.cafeteriaService.CanMeet)
|
||||
p.castleService = castle.NewService(p.design.castle)
|
||||
p.castleService.AttachTotalWarTextCheck(p.checkProfileText)
|
||||
@@ -69,6 +79,9 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
|
||||
}
|
||||
return ctx.Publish(command.Event{ID: "totalwar:" + identity, Topic: deck.PopularityTopic, Payload: payload})
|
||||
})
|
||||
p.castleService.AttachTotalWarSettled(func(ctx command.Context, total uint64) error {
|
||||
return p.recordMissions(ctx, []conditions.Event{{Type: conditions.TotalWarTryCount, Count: 1}, {Type: conditions.TotalWarResultScore, Sub: total, Count: 1}})
|
||||
})
|
||||
p.castleService.AttachCurrentPack(p.worldService.CurrentPackID)
|
||||
p.castleService.AttachEvidence(p.battleService.SettlementEvidence)
|
||||
p.castleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) {
|
||||
|
||||
@@ -5,7 +5,10 @@ import (
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) multiplayerPVP(ctx command.Context) error {
|
||||
@@ -29,7 +32,8 @@ func (p *playerAssembly) multiplayerPVP(ctx command.Context) error {
|
||||
Buffs: func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) {
|
||||
_, buffs, err := p.pictorialService.Snapshot(ctx)
|
||||
return buffs, err
|
||||
}}
|
||||
},
|
||||
CostumeCosts: p.colosseumCostumeCosts}
|
||||
p.pvpService, err = pvp.Open(ctx, p.design.pvp, public, p.pvpSource, builder,
|
||||
func(ctx command.Context, id string, cost []gamedata.BattleReward) error {
|
||||
_, err := p.eventEconomy.Apply(ctx, id, pvpRewards(cost), nil)
|
||||
@@ -84,3 +88,19 @@ func pvpRewards(in []gamedata.BattleReward) []gamedata.Reward {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *playerAssembly) colosseumCostumeCosts(ctx command.Context) (map[uint64]uint64, error) {
|
||||
cancel := ctx.Cancellation
|
||||
if cancel == nil {
|
||||
cancel = context.Background()
|
||||
}
|
||||
costs := map[uint64]uint64{}
|
||||
err := p.shared.store.View(cancel, func(tx *shared.Tx) error {
|
||||
table, err := p.shared.colosseumCosts(tx, uint64(time.Now().UnixMilli()))
|
||||
for _, row := range table.Costumes {
|
||||
costs[row.ID] = row.Cost
|
||||
}
|
||||
return err
|
||||
})
|
||||
return costs, err
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bd2server/internal/server/design/schedule"
|
||||
"bd2server/internal/server/domain/battle/roguelike"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
@@ -26,6 +27,17 @@ func (s *sharedRuntime) consumeRogueRanking(ctx context.Context, event outbox.Pe
|
||||
}
|
||||
return s.rogueRanks.Publish(ctx, p)
|
||||
}
|
||||
|
||||
// rogueLikeBattleEvent names the roguelike pack from GameData and the
|
||||
// ROGUE_LIKE battle mode for McPackBattle.
|
||||
func (p *playerAssembly) rogueLikeBattleEvent() conditions.Event {
|
||||
return conditions.Event{Type: conditions.PackBattle, Sub: p.design.roguelike.Pack, Param: battleModeRogueLike, Count: 1}
|
||||
}
|
||||
|
||||
func (p *playerAssembly) recordRogueLikeBattle(ctx command.Context) error {
|
||||
return p.recordMission(ctx, p.rogueLikeBattleEvent())
|
||||
}
|
||||
|
||||
func (p *playerAssembly) rogueLike(ctx command.Context) error {
|
||||
owner, e := p.ProfileOwner(ctx)
|
||||
if e != nil {
|
||||
@@ -131,7 +143,8 @@ func (p *playerAssembly) rogueLike(ctx command.Context) error {
|
||||
hp := gamedata.AggregateStats(gamedata.BaseStats{Health: float64(c.Health)}, contributions).Health
|
||||
return uint64(hp), nil
|
||||
},
|
||||
Ranking: p.rogueRanking(),
|
||||
Ranking: p.rogueRanking(),
|
||||
OnBattle: p.recordRogueLikeBattle,
|
||||
Publish: func(ctx command.Context, season, score, damage, version uint64) error {
|
||||
profile, e := p.PublicProfile(ctx, owner)
|
||||
if e != nil {
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/commerce"
|
||||
"bd2server/internal/server/domain/commerce/gacha"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/domain/notice"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
@@ -17,7 +16,6 @@ import (
|
||||
"bd2server/internal/server/storage/account"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) session(ctx command.Context) error {
|
||||
@@ -32,6 +30,11 @@ func (p *playerAssembly) session(ctx command.Context) error {
|
||||
if err := p.nickname(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
masterTitle, err := roster.OpenMasterTitleService(ctx, p.scope, p.nicknameService.CurrentNickname())
|
||||
if err != nil {
|
||||
return fmt.Errorf("load master title: %w", err)
|
||||
}
|
||||
p.masterTitleService = masterTitle
|
||||
if err := p.avatar(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -126,19 +129,9 @@ func (p *playerAssembly) session(ctx command.Context) error {
|
||||
if p.pvpService != nil {
|
||||
p.handlers = append([]session.Handler{p.pvpService}, p.handlers...)
|
||||
}
|
||||
p.observers = []session.ResponseObserver{p.achievementObserver, p.eventTasksService, p.mailService}
|
||||
featured := gacha.ActivePickupCostumes(p.design.regularGacha, p.options.calendars.GachaSeed, uint64(time.Now().UTC().UnixMilli()))
|
||||
limitedIDs := p.design.limitedCostumes.Excluding(featured)
|
||||
if len(limitedIDs) != 0 {
|
||||
if err := p.mailService.EnsureStarterLimitedCostumes(ctx, limitedIDs, time.Now().UTC()); err != nil {
|
||||
return fmt.Errorf("ensure account limited-costume entitlement: %w", err)
|
||||
}
|
||||
}
|
||||
prestigeIDs := p.design.prestigeCatalog.Giftable(func(key gamedata.CashProductKey) bool { return p.cashService.IsAvailable(ctx, key) })
|
||||
if len(prestigeIDs) != 0 {
|
||||
if err := p.mailService.EnsureStarterPrestigeSkins(ctx, prestigeIDs, time.Now().UTC()); err != nil {
|
||||
return fmt.Errorf("ensure account prestige-skin entitlement: %w", err)
|
||||
}
|
||||
p.observers = []session.ResponseObserver{p.achievementObserver, missionActionObserver{p}, p.eventTasksService, p.mailService}
|
||||
if err := p.mailService.AttachStarterGifts(ctx, p.starterGifts); err != nil {
|
||||
return fmt.Errorf("ensure account starter gifts: %w", err)
|
||||
}
|
||||
if p.initializeAccount {
|
||||
if err := ensureAccountStateInitialized(ctx,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/commerce/gacha"
|
||||
"bd2server/internal/server/domain/startergift"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) starterGifts(ctx command.Context) ([]startergift.Gift, error) {
|
||||
owned := map[uint64]bool{}
|
||||
for _, item := range p.ownedItems.All(ctx) {
|
||||
if item.Type == 45 && item.Count != 0 {
|
||||
owned[item.ID] = true
|
||||
}
|
||||
}
|
||||
return p.seeds.starterGifts.Resolve(startergift.Selection{
|
||||
Limited: p.design.limitedCostumes, Prestige: p.design.prestigeCatalog, Avatars: p.design.avatarProfile,
|
||||
Featured: gacha.ActivePickupCostumes(p.design.regularGacha, p.options.calendars.GachaSeed, uint64(time.Now().UTC().UnixMilli())),
|
||||
CashAvailable: func(key gamedata.CashProductKey) bool { return p.cashService.IsAvailable(ctx, key) },
|
||||
OwnedPrestige: owned,
|
||||
})
|
||||
}
|
||||
@@ -4,13 +4,11 @@ import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/commerce/gacha"
|
||||
"bd2server/internal/server/domain/progression/missions"
|
||||
"bd2server/internal/server/domain/progression/conditions"
|
||||
"bd2server/internal/server/domain/progression/pictorial"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/domain/roster/deck"
|
||||
"bd2server/internal/server/domain/world"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
@@ -71,8 +69,11 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
|
||||
if err := p.gachaService.AttachStatistics(p.design.collectionStatistics); err != nil {
|
||||
return err
|
||||
}
|
||||
p.gachaService.AttachDrawMission(func(ctx command.Context, count uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, missions.ConditionGachaBuy, 0, count, p.worldService.MissionsUnlocked)
|
||||
p.gachaService.AttachDrawMission(func(ctx command.Context, groupID, count uint64) error {
|
||||
if err := p.recordMission(ctx, conditions.Event{Type: conditions.GachaBuy, Count: count}); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.recordMission(ctx, conditions.Event{Type: conditions.GachaGroupTry, Sub: groupID, Count: count})
|
||||
})
|
||||
var permanentBaseCharacters []roster.Character
|
||||
for _, c := range p.worldService.CharacterService().RawAll() {
|
||||
@@ -184,13 +185,5 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
|
||||
if err := p.login.AttachFriendshipAP(p.friendshipService); err != nil {
|
||||
return err
|
||||
}
|
||||
accountName, found, err := wire.Bytes(p.login.UserInfo, 2)
|
||||
if err != nil || !found || len(accountName) == 0 {
|
||||
return errors.New("account seed requires its existing display name for master title")
|
||||
}
|
||||
p.masterTitleService, err = roster.OpenMasterTitleService(ctx, p.scope, string(accountName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("load master title: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -21,7 +21,9 @@ func TestOwnedPrestigeUnlocksInteractionOnLoginAndWhenClaimed(t *testing.T) {
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
|
||||
var sourceTime uint64
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
p.ownedItems.AttachPrestigeIllustrations(nil)
|
||||
if err := p.ownedItems.AttachPrestigeIllustrations(ctx, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := p.ownedItems.GrantOnce(ctx, "historical-prestige", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}})
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("seed historical external ownership: %v", err)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// GameData 20261021182514 maps prestige4091 to costume4001. Native ItemInfo
|
||||
// calls AddPrestigeSkinInfo without clearing its cache; PrestigeSkinInfo clears
|
||||
// that cache and restores IsSet. Historical mission and mail grants can coexist.
|
||||
func TestPrestigeLoginSnapshotPreservesSelectionWithHistoricalDuplicateItems(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
var skin assets.Item
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
items, err := p.ownedItems.GrantOnce(ctx, "historical-mission-skin", []gamedata.BattleReward{{Type: 45, ID: 4091, Count: 1}})
|
||||
if err != nil || len(items) != 1 || items[0].Type != 45 || items[0].Count != 1 {
|
||||
t.Fatalf("initial skin acquisition: %v %v", items, err)
|
||||
}
|
||||
skin = items[0]
|
||||
info := appScalar(1, 4001)
|
||||
info = append(info, appScalar(2, 4091)...)
|
||||
info = append(info, appScalar(3, 1)...)
|
||||
info = append(info, appScalar(4, skin.TimeValue)...)
|
||||
request := wire.AppendBytes(appScalar(1, 1), 2, info)
|
||||
if _, _, handled, err := p.eventEconomy.Handle(ctx, "/PrestigeSkinSet", request); !handled || err != nil {
|
||||
t.Fatalf("select owned skin: handled=%v error=%v", handled, err)
|
||||
}
|
||||
duplicate := skin
|
||||
duplicate.InvenIndex, err = ctx.NewInstanceID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
duplicate.TimeValue++
|
||||
raw, err := json.Marshal(duplicate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ctx.State.PutEntry("items", "items", strconv.FormatUint(duplicate.InvenIndex, 10), raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
s.reopen(t)
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
skinCount := 0
|
||||
for _, item := range p.ownedItems.All(ctx) {
|
||||
if item.Type == 45 && item.ID == 4091 {
|
||||
skinCount++
|
||||
}
|
||||
}
|
||||
if skinCount != 2 {
|
||||
t.Fatalf("historical duplicate fixture was not reopened: %d", skinCount)
|
||||
}
|
||||
var previous []byte
|
||||
for i := range 2 {
|
||||
_, snapshot, handled, err := p.eventEconomy.Handle(ctx, "/PrestigeSkinInfo", appScalar(1, uint64(i+2)))
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("skin snapshot: handled=%v error=%v", handled, err)
|
||||
}
|
||||
rows := appRows(snapshot, 1)
|
||||
if len(rows) != 1 || appValue(rows[0], 1) != 4001 || appValue(rows[0], 2) != 4091 || appValue(rows[0], 3) != 1 || appValue(rows[0], 4) != skin.TimeValue {
|
||||
t.Fatalf("snapshot lost unique ownership, selection, or acquisition time: %x", snapshot)
|
||||
}
|
||||
if i > 0 && !bytes.Equal(previous, snapshot) {
|
||||
t.Fatal("repeated snapshot changed skin state")
|
||||
}
|
||||
previous = snapshot
|
||||
_, inventory, handled, err := p.ownedItems.Handle(ctx, "/ItemInfo", appScalar(1, uint64(i+4)))
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("inventory snapshot: handled=%v error=%v", handled, err)
|
||||
}
|
||||
ordinaryIllustration := false
|
||||
for _, row := range appRows(inventory, 1) {
|
||||
if appValue(row, 3) == 45 {
|
||||
t.Fatal("inventory snapshot replays a prestige acquisition")
|
||||
}
|
||||
if appValue(row, 3) == 25 && appValue(row, 2) == 181 {
|
||||
ordinaryIllustration = true
|
||||
}
|
||||
}
|
||||
if !ordinaryIllustration {
|
||||
t.Fatal("inventory snapshot lost ordinary lobby ownership")
|
||||
}
|
||||
}
|
||||
})
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
items, err := p.ownedItems.GrantOnce(ctx, "another-mail-same-skin", []gamedata.BattleReward{{Type: 45, ID: 4091, Count: 1}})
|
||||
if err != nil || len(items) != 0 {
|
||||
t.Fatalf("owned skin replayed acquisition: %v %v", items, err)
|
||||
}
|
||||
items, err = p.ownedItems.GrantOnce(ctx, "new-mail-skin", []gamedata.BattleReward{{Type: 45, ID: 3892, Count: 2}, {Type: 45, ID: 3892, Count: 1}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
skins := 0
|
||||
for _, item := range items {
|
||||
if item.Type == 45 {
|
||||
skins++
|
||||
if item.ID != 3892 || item.Count != 1 {
|
||||
t.Fatalf("invalid unique acquisition: %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
if skins != 1 {
|
||||
t.Fatalf("new skin must emit one acquisition: %v", items)
|
||||
}
|
||||
if retry, err := p.ownedItems.GrantOnce(ctx, "new-mail-skin", []gamedata.BattleReward{{Type: 45, ID: 3892, Count: 2}, {Type: 45, ID: 3892, Count: 1}}); err != nil || len(retry) != 0 {
|
||||
t.Fatalf("retry replayed acquisition: %v %v", retry, err)
|
||||
}
|
||||
})
|
||||
s.reopen(t)
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
skinCount := 0
|
||||
for _, item := range p.ownedItems.All(ctx) {
|
||||
if item.Type == 45 && item.ID == 3892 {
|
||||
skinCount++
|
||||
if item.Count != 1 {
|
||||
t.Fatalf("persisted skin count is %d", item.Count)
|
||||
}
|
||||
}
|
||||
}
|
||||
if skinCount != 1 {
|
||||
t.Fatalf("new skin ownership was not persisted once: %d", skinCount)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -43,7 +43,7 @@ func profileGrant(g *puzzleGameplay, rewards ...gamedata.Reward) {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, fmt.Sprintf("profile-test:%d", g.seq), nil, rewards); err != nil {
|
||||
if _, err := g.owner.assembly.eventEconomy.Apply(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, fmt.Sprintf("profile-test:%d", g.seq), nil, rewards); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
@@ -416,7 +416,7 @@ func TestSupporterRegistrationPreservesSlotsAndReturnsOwnedBattleCharacter(t *te
|
||||
}
|
||||
// Current CostumeTable101 is permanent character UniqueChar1. The
|
||||
// integration starter only has story characters, so grant actual ownership.
|
||||
if _, err := g.owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "profile-supporter-fixture", []uint64{101}, g.factory.design.rewardCostumes); err != nil {
|
||||
if _, err := g.owner.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, "profile-supporter-fixture", []uint64{101}, g.factory.design.rewardCostumes); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -3,18 +3,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
@@ -108,7 +103,7 @@ func (g *puzzleGameplay) grantTokens(count uint64) {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
if _, err := g.owner.assembly.ownedItems.GrantOnce(ctx, fmt.Sprintf("puzzle-budget-%d", g.seq), []gamedata.BattleReward{{Type: 8, ID: 2021, Count: count}}); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
@@ -124,7 +119,7 @@ func (g *puzzleGameplay) cost(field int, count uint64) []byte {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx}, 8, 2021, count)
|
||||
items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, 8, 2021, count)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
@@ -202,274 +197,3 @@ func puzzleWordReward(t *testing.T, response []byte, itemType, id, count uint64)
|
||||
// currency 44 x 500, stage-2 material 8/113 x 600, and a terminal stage 12.
|
||||
// This exercises actual client requests, the production reward economy and
|
||||
// the account SQLite transaction rather than an isolated imitation of play.
|
||||
func TestPuzzleMaximumOpenWordsRenewalAndPersistence(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
var schedule events.Schedule
|
||||
for _, candidate := range owner.assembly.eventRegistry.List() {
|
||||
if candidate.Type == 17 && candidate.ID == 10 && candidate.Start <= time.Now().UnixMilli() && candidate.End > time.Now().UnixMilli() {
|
||||
schedule = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if schedule.UID == 0 {
|
||||
t.Fatal("current puzzle event 10 schedule required")
|
||||
}
|
||||
uid := appScalar(2, schedule.UID)
|
||||
g.call("/LoginUser", nil)
|
||||
var loginTask []byte
|
||||
for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
|
||||
if appValue(row, 1) == 30030 && appValue(row, 3) == 300301 {
|
||||
loginTask = row
|
||||
}
|
||||
}
|
||||
if appValue(loginTask, 4) != 1 || appValue(loginTask, 5) != 0 {
|
||||
t.Fatalf("puzzle login token mission did not complete: %x", loginTask)
|
||||
}
|
||||
mission := append(appScalar(3, 2), appScalar(4, 30030)...)
|
||||
mission = append(mission, appScalar(5, 300301)...)
|
||||
mission = append(mission, appScalar(6, 30030)...)
|
||||
claimRequest := g.request("/MissionClear", mission)
|
||||
beforeTokens := g.itemCount(8, 2021)
|
||||
g.execute(claimRequest, false)
|
||||
if got := g.itemCount(8, 2021); got != beforeTokens+2 {
|
||||
t.Fatalf("puzzle login mission delivered %d tokens, want %d", got, beforeTokens+2)
|
||||
}
|
||||
claimRequest.Identity.RequestID += "-replay"
|
||||
g.execute(claimRequest, false)
|
||||
if got := g.itemCount(8, 2021); got != beforeTokens+2 {
|
||||
t.Fatal("mission replay delivered tokens twice")
|
||||
}
|
||||
if beforeTokens != 0 {
|
||||
t.Fatal("fresh account unexpectedly contains puzzle tokens")
|
||||
}
|
||||
g.grantTokens(2)
|
||||
first := g.info(schedule.UID)
|
||||
board := puzzleNumbers(t, first, 3)
|
||||
sorted := slices.Clone(board)
|
||||
slices.Sort(sorted)
|
||||
if appValue(first, 2) != 1 || len(sorted) != 25 || sorted[0] != 1 || sorted[24] != 25 || len(slices.Compact(sorted)) != 25 {
|
||||
t.Fatalf("fresh stage has an invalid client board: %x", first)
|
||||
}
|
||||
bad := g.execute(g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 3)...)), true)
|
||||
for _, detail := range []string{"/MiniPuzzleAllOpen", fmt.Sprintf("uid=%d", schedule.UID), "submitted=3", "expected=4", "unit_cost=1"} {
|
||||
if !strings.Contains(string(bad), detail) {
|
||||
t.Fatalf("cost diagnostic missing %q: %s", detail, bad)
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("invalid maximum-open cost changed progress or inventory")
|
||||
}
|
||||
forged := append(appScalar(1, 1), appScalar(2, 2021)...)
|
||||
forged = append(forged, appScalar(3, 8)...)
|
||||
forged = append(forged, appScalar(4, 1)...)
|
||||
fields := append(slices.Clone(uid), appScalar(3, board[0])...)
|
||||
g.execute(g.request("/MiniPuzzleOpen", append(fields, appMessage(4, forged)...)), true)
|
||||
if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("forged stack consumption changed puzzle progress or inventory")
|
||||
}
|
||||
maximum := g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 4)...))
|
||||
response := g.execute(maximum, false)
|
||||
after := puzzleResponseState(t, response, 2)
|
||||
opened := puzzleNumbers(t, after, 4)
|
||||
if appValue(after, 2) != 1 || len(opened) != 4 || len(slices.Compact(slices.Sorted(slices.Values(opened)))) != 4 || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatalf("four-token maximum-open did not open and charge four cells: %x", response)
|
||||
}
|
||||
if !bytes.Equal(first, puzzleResponseState(t, response, 1)) || !slices.Equal(board, puzzleNumbers(t, after, 3)) {
|
||||
t.Fatal("maximum-open rearranged the current board or lost its before snapshot")
|
||||
}
|
||||
g.reopen()
|
||||
if !bytes.Equal(after, g.info(schedule.UID)) {
|
||||
t.Fatal("restart lost partial puzzle progress")
|
||||
}
|
||||
maximum.Identity.RequestID += "-reopened-domain-replay"
|
||||
if got := g.execute(maximum, false); !bytes.Equal(got, response) || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatal("restart replay changed the response or charged twice")
|
||||
}
|
||||
g.grantTokens(400)
|
||||
beforeWordCurrency := g.wordCurrency()
|
||||
var completed []byte
|
||||
for id := uint64(1); id <= 7; id++ {
|
||||
if slices.Contains(opened, id) {
|
||||
continue
|
||||
}
|
||||
fields := append(slices.Clone(uid), appScalar(3, id)...)
|
||||
fields = append(fields, g.cost(4, 1)...)
|
||||
result := g.call("/MiniPuzzleOpen", fields)
|
||||
opened = puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)
|
||||
if len(appRows(result, 5)) > 0 {
|
||||
completed = result
|
||||
}
|
||||
}
|
||||
puzzleWordReward(t, completed, 44, 0, 500)
|
||||
if g.wordCurrency() != beforeWordCurrency+500 {
|
||||
t.Fatal("word completion did not credit its currency to durable account state")
|
||||
}
|
||||
if len(opened) >= 25 {
|
||||
t.Fatal("word-only fixture unexpectedly opened the entire board")
|
||||
}
|
||||
tokens := g.itemCount(8, 2021)
|
||||
renewed := g.call("/MiniPuzzleRenew", uid)
|
||||
if appValue(puzzleResponseState(t, renewed, 1), 2) != 1 || appValue(puzzleResponseState(t, renewed, 2), 2) != 2 || len(puzzleNumbers(t, puzzleResponseState(t, renewed, 2), 4)) != 0 || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("word-complete renewal did not abandon incidental cells without charging")
|
||||
}
|
||||
beforeMaterial := g.itemCount(8, 113)
|
||||
fullRequest := g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...))
|
||||
full := g.execute(fullRequest, false)
|
||||
puzzleWordReward(t, full, 8, 113, 600)
|
||||
if appValue(puzzleResponseState(t, full, 1), 2) != 2 || appValue(puzzleResponseState(t, full, 2), 2) != 3 || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 {
|
||||
t.Fatal("full second board did not settle its word reward and automatically advance")
|
||||
}
|
||||
g.reopen()
|
||||
fullRequest.Identity.RequestID += "-domain-reward-replay"
|
||||
if replay := g.execute(fullRequest, false); !bytes.Equal(replay, full) || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 || g.wordCurrency() != beforeWordCurrency+500 {
|
||||
t.Fatal("full-board replay after restart duplicated a cost or reward")
|
||||
}
|
||||
for stage := uint64(3); stage <= 12; stage++ {
|
||||
beforeTickets := g.itemCount(8, 1000)
|
||||
full = g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...))
|
||||
wantStage := min(stage+1, uint64(12))
|
||||
if appValue(puzzleResponseState(t, full, 1), 2) != stage || appValue(puzzleResponseState(t, full, 2), 2) != wantStage {
|
||||
t.Fatalf("stage %d did not advance correctly: %x", stage, full)
|
||||
}
|
||||
if stage == 7 {
|
||||
puzzleWordReward(t, full, 8, 1000, 10)
|
||||
if g.itemCount(8, 1000) != beforeTickets+10 {
|
||||
t.Fatal("stage-seven word tickets were not credited to inventory")
|
||||
}
|
||||
}
|
||||
}
|
||||
puzzleWordReward(t, full, 4, 0, 100000)
|
||||
final := g.info(schedule.UID)
|
||||
if appValue(final, 2) != 12 || len(puzzleNumbers(t, final, 4)) != 25 {
|
||||
t.Fatal("terminal puzzle did not retain all completed cells")
|
||||
}
|
||||
tokens = g.itemCount(8, 2021)
|
||||
g.execute(g.request("/MiniPuzzleRenew", uid), true)
|
||||
g.execute(g.request("/MiniPuzzleAllOpen", uid), true)
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("terminal operations changed assets or advanced beyond the final stage")
|
||||
}
|
||||
g.reopen()
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("terminal puzzle progress or token balance changed after reopening SQLite")
|
||||
}
|
||||
calendar := g.owner.assembly.eventRegistry.List()
|
||||
for index := range calendar {
|
||||
if calendar[index].UID == schedule.UID {
|
||||
calendar[index].End = time.Now().Add(-time.Minute).UnixMilli()
|
||||
}
|
||||
}
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) {
|
||||
t.Fatal("expired info query erased previously completed progress")
|
||||
}
|
||||
closed := g.execute(g.request("/MiniPuzzleRenew", uid), true)
|
||||
if !strings.Contains(string(closed), "event is closed") || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("expired puzzle allowed mutation or charged resources")
|
||||
}
|
||||
}
|
||||
|
||||
// ResourceTable 2021's current stack limit is 9999. A real grant of 10001
|
||||
// creates two stacks; consuming 9997 leaves two tokens in each. The native
|
||||
// maximum-open request must sum both concrete stacks while each schedule
|
||||
// retains its own board and open-cell history.
|
||||
func TestPuzzleMaximumOpenUsesSplitStacksAndSeparateSchedules(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
calendar := owner.assembly.eventRegistry.List()
|
||||
var schedule events.Schedule
|
||||
for _, candidate := range calendar {
|
||||
if candidate.Type == 17 && candidate.ID == 10 {
|
||||
schedule = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if schedule.UID == 0 {
|
||||
t.Fatal("current puzzle schedule required")
|
||||
}
|
||||
second := schedule
|
||||
second.UID = 2000000010
|
||||
calendar = append(calendar, second)
|
||||
if err := owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
uid := appScalar(2, schedule.UID)
|
||||
firstBoard, secondBoard := g.info(schedule.UID), g.info(second.UID)
|
||||
g.grantTokens(10001)
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx}
|
||||
spent, err := owner.assembly.ownedItems.SelectMutable(ctx, 8, 2021, 9997)
|
||||
if err == nil {
|
||||
err = owner.assembly.ownedItems.Consume(ctx, spent)
|
||||
}
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cost := g.cost(3, 4)
|
||||
stacks := appRows(cost, 3)
|
||||
if len(stacks) != 2 || appValue(stacks[0], 4) != 2 || appValue(stacks[1], 4) != 2 {
|
||||
t.Fatalf("split-stack fixture is not two independent two-token entries: %x", cost)
|
||||
}
|
||||
duplicate := append(appMessage(3, stacks[0]), appMessage(3, stacks[0])...)
|
||||
g.execute(g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), duplicate...)), true)
|
||||
if !bytes.Equal(firstBoard, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("duplicate submitted stack changed progress or token balance")
|
||||
}
|
||||
// A failed request rebuilds the production assembly from SQLite and its
|
||||
// configured calendar; reinstall only the second test schedule afterward.
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), cost...))
|
||||
if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 4 || g.itemCount(8, 2021) != 0 || !bytes.Equal(secondBoard, g.info(second.UID)) {
|
||||
t.Fatal("maximum-open did not consume both stacks or mixed the two schedule states")
|
||||
}
|
||||
firstAfter := g.info(schedule.UID)
|
||||
g.grantTokens(1)
|
||||
board := puzzleNumbers(t, secondBoard, 3)
|
||||
fields := append(appScalar(2, second.UID), appScalar(3, board[0])...)
|
||||
fields = append(fields, g.cost(4, 1)...)
|
||||
result = g.call("/MiniPuzzleOpen", fields)
|
||||
if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 1 || !bytes.Equal(firstAfter, g.info(schedule.UID)) || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatal("single-open used another schedule's cells or did not charge its token")
|
||||
}
|
||||
g.reopen()
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(firstAfter, g.info(schedule.UID)) || len(puzzleNumbers(t, g.info(second.UID), 4)) != 1 {
|
||||
t.Fatal("SQLite restart merged independent puzzle schedule progress")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/world/progress"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// QuestReplayPopupUI accepts PackTable main quest 1 with is_retry once hard (2)
|
||||
// is complete; QuestPopupUI hides rewards while QuestPacket replaces the active
|
||||
// quest with QuestRetryDBInfo from accept/clear/give-up and PackInfo field 7.
|
||||
func TestMainQuestReplayTracksProgressWithoutRewardsAndRestoresSelection(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
mainQuests := factory.design.world.Story.Packs[1].MainQuestIDs
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "fixture"}, State: tx}
|
||||
state := owner.assembly.progressState
|
||||
for difficulty := 0; difficulty <= 2; difficulty++ {
|
||||
for _, id := range mainQuests {
|
||||
if err := state.ClearQuest(ctx, id, 1, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
completed := progress.QuestSelection{Difficulty: 2}
|
||||
if err := state.SelectQuest(ctx, 1, completed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := owner.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := player.New(accounts[0], owner, player.Limits{CompletedReceipts: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := runtime.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
seq := uint64(0)
|
||||
request := func(path string, fields ...uint64) player.Command {
|
||||
seq++
|
||||
body := appScalar(1, seq)
|
||||
for i := 0; i+1 < len(fields); i += 2 {
|
||||
body = append(body, appScalar(int(fields[i]), fields[i+1])...)
|
||||
}
|
||||
c := registryCommand(accounts[0], fmt.Sprintf("replay-%d%s", seq, path), path, body)
|
||||
c.Identity.SessionID = "replay"
|
||||
return c
|
||||
}
|
||||
run := func(path string, fields ...uint64) []byte {
|
||||
t.Helper()
|
||||
return registryExecute(t, runtime, request(path, fields...)).Responses[0].Body
|
||||
}
|
||||
rejected := func(path string, fields ...uint64) {
|
||||
t.Helper()
|
||||
future, err := runtime.Submit(context.Background(), request(path, fields...))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := future.Wait(context.Background()); err == nil {
|
||||
t.Fatalf("%s %v was accepted", path, fields)
|
||||
}
|
||||
}
|
||||
packReplay := func() (retrying bool, replays [][]byte) {
|
||||
t.Helper()
|
||||
info := run("/PackInfo")
|
||||
for _, row := range appRows(info, 1) {
|
||||
if appValue(row, 1) == 1 {
|
||||
retrying = appValue(row, 9) == 1
|
||||
}
|
||||
}
|
||||
return retrying, appRows(info, 7)
|
||||
}
|
||||
if retrying, replays := packReplay(); retrying || len(replays) != 0 {
|
||||
t.Fatal("a pack without a replay reported one")
|
||||
}
|
||||
first, second := uint64(mainQuests[0]), uint64(mainQuests[1])
|
||||
rejected("/QuestAccept", 2, second, 3, 1, 4, 1, 6, 1)
|
||||
accepted := appRows(run("/QuestAccept", 2, first, 3, 1, 4, 1, 6, 1, 7, 1), 5)
|
||||
if len(accepted) != 1 || appValue(accepted[0], 1) != 1 || appValue(accepted[0], 2) != 1 || appValue(accepted[0], 3) != first || appValue(accepted[0], 6) != 1 {
|
||||
t.Fatalf("accept did not start a hard replay with battle skip: %x", accepted)
|
||||
}
|
||||
run("/QuestUpdate", 2, first, 3, 1, 4, 3)
|
||||
run("/QuestRetryBattleSkipSave", 2, 1, 3, 0)
|
||||
retrying, replays := packReplay()
|
||||
if !retrying || len(replays) != 1 || appValue(replays[0], 3) != first || appValue(replays[0], 5) != 3 || appValue(replays[0], 6) != 0 {
|
||||
t.Fatalf("relogin lost replay progress or battle skip toggle: retry=%v %x", retrying, replays)
|
||||
}
|
||||
continued := appRows(run("/QuestAccept", 2, first, 3, 1, 4, 1, 6, 1), 5)
|
||||
if len(continued) != 1 || appValue(continued[0], 5) != 3 {
|
||||
t.Fatalf("continuing the replay discarded its progress: %x", continued)
|
||||
}
|
||||
|
||||
gold := owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
items := appItemTotals(run("/ItemInfo"))
|
||||
clear := run("/QuestClear", 2, first, 3, 1)
|
||||
next := appRows(clear, 16)
|
||||
if len(appRows(clear, 1)) != 1 || len(appRows(clear, 1)[0]) != 0 || len(next) != 1 || appValue(next[0], 3) != second || appValue(next[0], 2) != 1 {
|
||||
t.Fatalf("replay clear paid rewards or did not advance: %x", clear)
|
||||
}
|
||||
if owner.assembly.wallet.Snapshot(command.Context{}).Gold != gold || !maps.Equal(appItemTotals(run("/ItemInfo")), items) {
|
||||
t.Fatal("replay clear changed owned rewards")
|
||||
}
|
||||
rejected("/QuestClear", 2, first, 3, 1)
|
||||
|
||||
ended := appRows(run("/QuestGiveUp", 2, second, 3, 1), 5)
|
||||
if len(ended) != 1 || appValue(ended[0], 1) != 1 || appValue(ended[0], 3) != 0 {
|
||||
t.Fatalf("give up did not end the client replay: %x", ended)
|
||||
}
|
||||
if retrying, replays := packReplay(); retrying || len(replays) != 0 {
|
||||
t.Fatal("abandoned replay survived")
|
||||
}
|
||||
if selection, _ := state.Selection(1); selection != completed {
|
||||
t.Fatalf("give up left replay selection %+v", selection)
|
||||
}
|
||||
rejected("/QuestRetryBattleSkipSave", 2, 1, 3, 1)
|
||||
|
||||
run("/QuestAccept", 2, first, 3, 1, 6, 1)
|
||||
quest := first
|
||||
for range mainQuests {
|
||||
retry := appRows(run("/QuestClear", 2, quest, 3, 1), 16)
|
||||
if len(retry) != 1 {
|
||||
t.Fatalf("replay clear of quest %d omitted QuestRetryInfo", quest)
|
||||
}
|
||||
if quest = appValue(retry[0], 3); quest == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if quest != 0 {
|
||||
t.Fatal("replay did not end after the final main quest")
|
||||
}
|
||||
if retrying, replays := packReplay(); retrying || len(replays) != 0 {
|
||||
t.Fatal("finished replay survived")
|
||||
}
|
||||
if selection, _ := state.Selection(1); selection != completed {
|
||||
t.Fatalf("finished replay left selection %+v", selection)
|
||||
}
|
||||
}
|
||||
@@ -126,5 +126,11 @@ func (p *playerAssembly) roomProfile(ctx command.Context) ([]byte, error) {
|
||||
use = wire.AppendVarint(use, index+3, value)
|
||||
}
|
||||
fish := p.fishingService.Profile()
|
||||
return json.Marshal(room.Profile{UserInfo: user, AvatarUseInfo: use, RodID: int64(fish.RodID), BoatLevel: int64(fish.BoatLevel), BoatSkinID: int64(fish.BoatSkinID), FishingMaps: fish.Maps})
|
||||
var motions []uint64
|
||||
for _, item := range p.ownedItems.All(ctx) {
|
||||
if item.Type == 50 && item.Count > 0 {
|
||||
motions = append(motions, item.ID)
|
||||
}
|
||||
}
|
||||
return json.Marshal(room.Profile{UserInfo: user, AvatarUseInfo: use, AvatarMotions: motions, SquareUnlocked: p.worldService.CanEnterFieldPackType(ctx, 11), RodID: int64(fish.RodID), BoatLevel: int64(fish.BoatLevel), BoatSkinID: int64(fish.BoatSkinID), FishingMaps: fish.Maps})
|
||||
}
|
||||
@@ -35,6 +35,7 @@ func openRealtime(c *configuration, registry *playerRegistry, game *session.Serv
|
||||
results.endpoints = []eventplay.RelayEndpoint{{Region: "1", Host: config.PublicHost, TCPPort: strconv.Itoa(config.TCPPort)}}
|
||||
var transport atomic.Pointer[realtime.Server]
|
||||
rooms, err := room.New(room.Config{AdvertisedHost: config.PublicHost, TCPPort: config.TCPPort, UDPPort: config.UDPPort,
|
||||
SquareChannels: int(registry.factory.design.avatarProfile.SquareChannels), SquareChannelCapacity: int(registry.factory.design.avatarProfile.SquareChannelCapacity),
|
||||
Publish: func(frames []room.Delivery) {
|
||||
if server := transport.Load(); server != nil {
|
||||
server.Deliver(frames)
|
||||
|
||||
@@ -70,7 +70,7 @@ func (t *realtimeTickets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid ticket request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if request.Channel != room.Matching && request.Channel != room.Action && request.Channel != room.Defense && request.Channel != room.Fishing {
|
||||
if request.Channel != room.Matching && request.Channel != room.Action && request.Channel != room.Defense && request.Channel != room.Fishing && request.Channel != room.Square {
|
||||
http.Error(w, "invalid channel", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -182,3 +182,7 @@ func (t *realtimeTickets) Consume(ctx context.Context, token, channel, instance
|
||||
func (t *realtimeTickets) Validate(ctx context.Context, p room.Principal) error {
|
||||
return t.game.ValidatePrincipal(ctx, session.Principal{AccountID: p.AccountID, SessionID: p.SessionID, Generation: p.Generation})
|
||||
}
|
||||
|
||||
func (t *realtimeTickets) RecordActivity(p room.Principal) {
|
||||
t.game.RecordActivity(session.Principal{AccountID: p.AccountID, SessionID: p.SessionID, Generation: p.Generation})
|
||||
}
|
||||
@@ -17,7 +17,9 @@ import (
|
||||
|
||||
func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
for _, scenario := range []struct {
|
||||
// Each scenario owns its account: trap commands restart their request IDs,
|
||||
// so sharing one account would replay the previous scenario's receipts.
|
||||
for i, scenario := range []struct {
|
||||
name string
|
||||
costume uint64
|
||||
goldThreadPerCopy uint64
|
||||
@@ -26,7 +28,7 @@ func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *test
|
||||
{"earned", 1401, 2},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[i], owner: openNicknamePlayer(t, factory, accounts[i])}
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
grant := func(key string, count uint64) []byte {
|
||||
t.Helper()
|
||||
@@ -114,7 +116,7 @@ func TestCommunityRewardCreditsOnceAndRestoresPerAccountClaims(t *testing.T) {
|
||||
displayed += appValue(reward, 4)
|
||||
}
|
||||
}
|
||||
// CommunityWebLinkTable 0 in GameData 20261012190548 advertises 100 free diamonds.
|
||||
// CommunityWebLinkTable 0 in GameData 20261021182514 advertises 100 free diamonds.
|
||||
if displayed != 100 || a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry != before+100 {
|
||||
t.Fatal("community reward shown by the client was not credited to spendable diamonds")
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ func TestNativeRoomVisitPrivacyOwnedLayoutAndPopularityAreDurable(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := actor.assembly.collection.GrantCostumes(command.Context{State: tx}, "room-costume-fixture", []uint64{101}, factory.design.rewardCostumes); err != nil {
|
||||
if _, err := actor.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "room-costume-fixture", []uint64{101}, factory.design.rewardCostumes); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := actor.assembly.ownedItems.GrantOnce(command.Context{State: tx}, "room-decoration-fixture", []gamedata.BattleReward{{Type: 27, ID: 101, Count: 1}})
|
||||
items, err := actor.assembly.ownedItems.GrantOnce(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "room-decoration-fixture", []gamedata.BattleReward{{Type: 27, ID: 101, Count: 1}})
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
)
|
||||
|
||||
type seedInstanceIDs struct {
|
||||
Characters map[uint64]uint64 `json:"characters"`
|
||||
Costumes map[uint64]uint64 `json:"costumes"`
|
||||
Items map[uint64]uint64 `json:"items"`
|
||||
}
|
||||
|
||||
func (p *playerAssembly) seedInstances(ctx command.Context) error {
|
||||
raw, found, err := ctx.State.LoadEntry("bootstrap", "instances", "seeds")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ids := seedInstanceIDs{Characters: map[uint64]uint64{}, Costumes: map[uint64]uint64{}, Items: map[uint64]uint64{}}
|
||||
if found {
|
||||
if err := stateio.RequireExactJSONObject(raw, "characters", "costumes", "items"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &ids); err != nil {
|
||||
return err
|
||||
}
|
||||
if ids.Characters == nil || ids.Costumes == nil || ids.Items == nil {
|
||||
return errors.New("account seed: invalid instance mapping")
|
||||
}
|
||||
} else if !p.initializeAccount {
|
||||
return errors.New("account seed: global instance mapping missing; offline migration required")
|
||||
}
|
||||
register := func(values map[uint64]uint64, old, class uint64) error {
|
||||
if old == 0 {
|
||||
return nil
|
||||
}
|
||||
if id, exists := values[old]; exists {
|
||||
if id&(roster.CharmCharacterIndexBase-1) == 0 || id&^(roster.CharmCharacterIndexBase-1) != class {
|
||||
return fmt.Errorf("account seed: invalid instance %d", old)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if found {
|
||||
return fmt.Errorf("account seed: unmapped instance %d", old)
|
||||
}
|
||||
id, err := ctx.NewInstanceID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values[old] = id | class
|
||||
return nil
|
||||
}
|
||||
for _, character := range p.starter.Characters {
|
||||
if err := register(ids.Characters, character.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := register(ids.Characters, p.worldSeed.RewardCharacter.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, character := range p.worldSeed.StoryCharacters {
|
||||
if err := register(ids.Characters, character.InvenIndex, roster.StoryCharacterIndexBase); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, costume := range p.starter.Costumes {
|
||||
if err := register(ids.Costumes, costume.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := register(ids.Costumes, p.worldSeed.RewardCostume.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range p.starter.Items {
|
||||
if err := register(ids.Items, item.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, item := range p.starter.OwnedItems {
|
||||
if err := register(ids.Items, item.InvenIndex, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
seen := make(map[uint64]bool)
|
||||
for _, values := range []map[uint64]uint64{ids.Characters, ids.Costumes, ids.Items} {
|
||||
for _, id := range values {
|
||||
if seen[id] {
|
||||
return fmt.Errorf("account seed: duplicate instance %d", id)
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
raw, err = json.Marshal(ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.State.PutEntry("bootstrap", "instances", "seeds", raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
remap := func(values map[uint64]uint64, old uint64) (uint64, error) {
|
||||
if old == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
id, exists := values[old]
|
||||
if !exists || id == 0 {
|
||||
return 0, fmt.Errorf("account seed: unresolved instance reference %d", old)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
character := func(value *roster.Character) error {
|
||||
value.InvenIndex, err = remap(ids.Characters, value.InvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.UseCostume, err = remap(ids.Costumes, value.UseCostume)
|
||||
return err
|
||||
}
|
||||
costume := func(value *roster.Costume) error {
|
||||
value.InvenIndex, err = remap(ids.Costumes, value.InvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.UseChar, err = remap(ids.Characters, value.UseChar)
|
||||
return err
|
||||
}
|
||||
for i := range p.starter.Characters {
|
||||
if err := character(&p.starter.Characters[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := character(&p.worldSeed.RewardCharacter); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range p.worldSeed.StoryCharacters {
|
||||
if err := character(&p.worldSeed.StoryCharacters[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i := range p.starter.Costumes {
|
||||
if err := costume(&p.starter.Costumes[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := costume(&p.worldSeed.RewardCostume); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range p.starter.Items {
|
||||
p.starter.Items[i].InvenIndex, err = remap(ids.Items, p.starter.Items[i].InvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i := range p.starter.OwnedItems {
|
||||
p.starter.OwnedItems[i].InvenIndex, err = remap(ids.Items, p.starter.OwnedItems[i].InvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i := range p.deckSeed.FieldDeck {
|
||||
entry := &p.deckSeed.FieldDeck[i]
|
||||
entry.CharacterInvenIndex, err = remap(ids.Characters, entry.CharacterInvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entry.CostumeInvenIndex, err = remap(ids.Costumes, entry.CostumeInvenIndex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,23 +1,35 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/server/domain/mail"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/domain/roster/deck"
|
||||
"bd2server/internal/server/domain/startergift"
|
||||
"bd2server/internal/server/domain/world"
|
||||
calendaradapter "bd2server/internal/server/protocol/calendar"
|
||||
loginprotocol "bd2server/internal/server/protocol/login"
|
||||
"bd2server/internal/server/protocol/staticdata"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type cashPackageLayouts struct {
|
||||
Version string `json:"version"`
|
||||
BundleVersion string `json:"bundle_version"`
|
||||
Layouts map[string]string `json:"layouts"`
|
||||
}
|
||||
|
||||
type seedCatalog struct {
|
||||
login *loginprotocol.LoginSeed
|
||||
starter *roster.Starter
|
||||
defaults *readonly.Seed
|
||||
mailbox *mail.Starter
|
||||
deck deck.Seed
|
||||
world world.Seed
|
||||
login *loginprotocol.LoginSeed
|
||||
starter *roster.Starter
|
||||
defaults *readonly.Seed
|
||||
mailbox *mail.Starter
|
||||
deck deck.Seed
|
||||
world world.Seed
|
||||
packageLayouts cashPackageLayouts
|
||||
starterGifts startergift.Catalog
|
||||
}
|
||||
|
||||
func loadSeeds(c *configuration) (*seedCatalog, error) {
|
||||
@@ -52,7 +64,29 @@ func loadSeeds(c *configuration) (*seedCatalog, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &seedCatalog{login: login, starter: starter, defaults: defaults, mailbox: mailbox, deck: deckSeed, world: worldSeed}, nil
|
||||
layouts, err := commonconfig.Load(filepath.Join(filepath.Dir(c.worldSeed), "cash_package_layouts.json"), cashPackageLayouts{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load cash package layouts: %w", err)
|
||||
}
|
||||
if layouts.Version != c.versions.GameVersion {
|
||||
return nil, fmt.Errorf("cash package layout game version mismatch: got %s, want %s", layouts.Version, c.versions.GameVersion)
|
||||
}
|
||||
if layouts.BundleVersion != c.versions.BundleVersion {
|
||||
return nil, fmt.Errorf("cash package layout bundle version mismatch: got %s, want %s", layouts.BundleVersion, c.versions.BundleVersion)
|
||||
}
|
||||
for resource, layout := range layouts.Layouts {
|
||||
if resource == "" || layout != "independent" && layout != "relay" {
|
||||
return nil, fmt.Errorf("invalid cash package layout %q: %q", resource, layout)
|
||||
}
|
||||
}
|
||||
gifts, err := commonconfig.Load(filepath.Join(filepath.Dir(c.worldSeed), "starter_gifts.json"), startergift.Catalog{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load starter gifts: %w", err)
|
||||
}
|
||||
if gifts.Version != c.versions.GameVersion || gifts.GameDataVersion != c.gameDataVersion {
|
||||
return nil, fmt.Errorf("starter gift game or GameData version mismatch")
|
||||
}
|
||||
return &seedCatalog{login: login, starter: starter, defaults: defaults, mailbox: mailbox, deck: deckSeed, world: worldSeed, packageLayouts: layouts, starterGifts: gifts}, nil
|
||||
}
|
||||
|
||||
func cloneSeed[T any](source *T) (*T, error) {
|
||||
|
||||
@@ -102,6 +102,7 @@ func Serve(args []string) (serveErr error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
shared.friends.AttachPresence(game.AccountOnline)
|
||||
|
||||
var authHandler http.Handler
|
||||
if authService != nil {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Colosseum costume costs (LocalText 40030034): costumes used by attackers of
|
||||
// Diamond III to Champion during the previous season are ranked by usage, and
|
||||
// ColosseumDefaultTable prices each rank bracket. The tally is per season.
|
||||
|
||||
const colosseumBattleTotal = "total"
|
||||
|
||||
func colosseumPopularityPrefix(season uint64) string {
|
||||
return fmt.Sprintf("colosseum:%020d:", season)
|
||||
}
|
||||
|
||||
type colosseumCostume struct {
|
||||
ID, Count, Rank, Cost uint64
|
||||
}
|
||||
|
||||
// colosseumCostTable is one previous-season tally; costumes absent from it use
|
||||
// ColosseumDefaults.CostDefault.
|
||||
type colosseumCostTable struct {
|
||||
Battles uint64
|
||||
Costumes []colosseumCostume
|
||||
}
|
||||
|
||||
func (t colosseumCostTable) cost(defaults gamedata.ColosseumDefaults, costume uint64) uint64 {
|
||||
for _, row := range t.Costumes {
|
||||
if row.ID == costume {
|
||||
return row.Cost
|
||||
}
|
||||
}
|
||||
return defaults.CostDefault
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) applyColosseumPopularity(tx *shared.Tx, battle pvp.BattleSettled) error {
|
||||
attacker := battle.Attacker
|
||||
if attacker.Rank == 0 {
|
||||
return nil
|
||||
}
|
||||
rank, err := s.pvpDesign.ColosseumRank(battle.Season, attacker.TopPercent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rank.RankGroup == 0 || rank.RankGroup > s.pvpDesign.Colosseum.PopularCostumeMinimumRankGroup {
|
||||
return nil
|
||||
}
|
||||
prefix := colosseumPopularityPrefix(battle.Season)
|
||||
used := map[uint64]bool{}
|
||||
if err = wire.Walk(attacker.Snapshot.FullDeck, func(f wire.Field) error {
|
||||
if f.Number != 2 {
|
||||
return nil
|
||||
}
|
||||
// FullDeck field 2 is the deck character with its selected costume id.
|
||||
costume, _, err := wire.Varint(f.Value, 5)
|
||||
if err != nil || costume == 0 {
|
||||
return fmt.Errorf("invalid colosseum deck costume")
|
||||
}
|
||||
used[costume] = true
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(used) == 0 {
|
||||
return fmt.Errorf("colosseum battle without deck costumes")
|
||||
}
|
||||
for costume := range used {
|
||||
if err = popularityCount(tx, "popularity_counts", prefix+fmt.Sprintf("%010d", costume), 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return popularityCount(tx, "popularity_counts", prefix+colosseumBattleTotal, 1)
|
||||
}
|
||||
|
||||
// previousColosseumSeason is the latest colosseum season already ended at.
|
||||
func (s *sharedRuntime) previousColosseumSeason(at uint64) (uint64, bool) {
|
||||
var best pvp.Season
|
||||
for _, season := range s.pvpSeasons {
|
||||
if season.Mode == pvp.Colosseum && season.End <= at && season.End > best.End {
|
||||
best = season
|
||||
}
|
||||
}
|
||||
return best.ID, best.ID != 0
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) colosseumCosts(tx *shared.Tx, at uint64) (colosseumCostTable, error) {
|
||||
var table colosseumCostTable
|
||||
season, found := s.previousColosseumSeason(at)
|
||||
if !found {
|
||||
return table, nil
|
||||
}
|
||||
prefix := colosseumPopularityPrefix(season)
|
||||
if err := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error {
|
||||
var count uint64
|
||||
if json.Unmarshal(row.Value, &count) != nil || count == 0 {
|
||||
return fmt.Errorf("invalid colosseum popularity")
|
||||
}
|
||||
key := strings.TrimPrefix(row.Key, prefix)
|
||||
if key == colosseumBattleTotal {
|
||||
table.Battles = count
|
||||
return nil
|
||||
}
|
||||
id, err := strconv.ParseUint(key, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return fmt.Errorf("invalid colosseum popularity key")
|
||||
}
|
||||
table.Costumes = append(table.Costumes, colosseumCostume{ID: id, Count: count})
|
||||
return nil
|
||||
}); err != nil {
|
||||
return table, err
|
||||
}
|
||||
slices.SortFunc(table.Costumes, func(a, b colosseumCostume) int {
|
||||
if a.Count != b.Count {
|
||||
if a.Count > b.Count {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.ID < b.ID {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
})
|
||||
for i := range table.Costumes {
|
||||
table.Costumes[i].Rank = uint64(i + 1)
|
||||
table.Costumes[i].Cost = s.pvpDesign.Colosseum.CostumeCost(table.Costumes[i].Rank)
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// colosseumPopularityBody encodes PopularCostumeInfoResponse for PCC_COLOSSEUM:
|
||||
// count_type0 is the previous season, which the client shows beside the cost.
|
||||
func colosseumPopularityBody(table colosseumCostTable) []byte {
|
||||
var body []byte
|
||||
for _, row := range table.Costumes {
|
||||
b := wire.AppendVarint(nil, 1, row.ID)
|
||||
b = wire.AppendVarint(b, 2, row.Count)
|
||||
b = wire.AppendVarint(b, 5, row.Rank)
|
||||
b = wire.AppendVarint(b, 6, row.Cost)
|
||||
body = wire.AppendBytes(body, 1, b)
|
||||
}
|
||||
var total []byte
|
||||
if table.Battles != 0 {
|
||||
total = wire.AppendVarint(nil, 2, table.Battles)
|
||||
}
|
||||
return wire.AppendBytes(body, 2, total)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
// Values from GameData 20261021182514 via gamedata_db.py: ColosseumDefaultTable
|
||||
// costDefault 30, rank boundaries 5/10/15/20 cost 50/45/40/35,
|
||||
// popularCostumeMinRankGroupId 6; ColosseumRankTable group 1 places Champion
|
||||
// (rankGroup 1) at top 0.1% and Diamond III (rankGroup 6) at top 30%, Ruby I
|
||||
// (rankGroup 7) at top 35%.
|
||||
func colosseumCostFixture(t *testing.T) *sharedRuntime {
|
||||
t.Helper()
|
||||
store, err := shared.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
design := &gamedata.PvpDesign{
|
||||
Colosseum: gamedata.ColosseumDefaults{CostDefault: 30, CostRankBoundaries: [4]uint64{5, 10, 15, 20}, CostRankValues: [4]uint64{50, 45, 40, 35}, PopularCostumeMinimumRankGroup: 6},
|
||||
ColosseumRankGroups: map[uint64]uint64{47: 1, 48: 1},
|
||||
ColosseumRanks: map[uint64][]gamedata.ColosseumRank{1: {
|
||||
{Group: 1, ID: 1, RankGroup: 1, TopPercent: 0.1},
|
||||
{Group: 1, ID: 16, RankGroup: 6, TopPercent: 30},
|
||||
{Group: 1, ID: 17, RankGroup: 7, TopPercent: 35},
|
||||
}},
|
||||
}
|
||||
seasons := []pvp.Season{{Mode: pvp.Colosseum, ID: 47, Start: 1000, End: 2000}, {Mode: pvp.Colosseum, ID: 48, Start: 2000, End: 3000}, {Mode: pvp.Mirror, ID: 9, Start: 0, End: 2500}}
|
||||
return &sharedRuntime{store: store, statistics: &gamedata.CollectionStatisticsDesign{}, pvpDesign: design, pvpSeasons: seasons}
|
||||
}
|
||||
|
||||
func colosseumAttack(season, rank uint64, percent float64, costumes ...uint64) pvp.BattleSettled {
|
||||
var deck []byte
|
||||
for _, costume := range costumes {
|
||||
deck = wire.AppendBytes(deck, 2, wire.AppendVarint(nil, 5, costume))
|
||||
}
|
||||
attacker := pvp.PublishedSnapshot{Mode: pvp.Colosseum, Season: season, Rank: rank, TopPercent: percent, Snapshot: pvp.FullSnapshot{FullDeck: deck}}
|
||||
return pvp.BattleSettled{Mode: pvp.Colosseum, Season: season, Attacker: attacker}
|
||||
}
|
||||
|
||||
func TestColosseumCostsRankPreviousSeasonDiamondAttackers(t *testing.T) {
|
||||
s := colosseumCostFixture(t)
|
||||
battles := []pvp.BattleSettled{
|
||||
colosseumAttack(47, 1, 0.1, 101, 102),
|
||||
colosseumAttack(47, 40, 30, 102, 103),
|
||||
colosseumAttack(47, 41, 30, 102),
|
||||
colosseumAttack(47, 90, 35, 104, 104),
|
||||
colosseumAttack(47, 0, 0, 105),
|
||||
colosseumAttack(48, 1, 0.1, 106),
|
||||
}
|
||||
for i := range 20 {
|
||||
battles = append(battles, colosseumAttack(47, 2, 0.1, 200+uint64(i)))
|
||||
}
|
||||
if err := s.store.Update(context.Background(), func(tx *shared.Tx) error {
|
||||
for _, battle := range battles {
|
||||
if err := s.applyColosseumPopularity(tx, battle); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var during, after colosseumCostTable
|
||||
if err := s.store.View(context.Background(), func(tx *shared.Tx) error {
|
||||
var err error
|
||||
if during, err = s.colosseumCosts(tx, 2500); err != nil {
|
||||
return err
|
||||
}
|
||||
after, err = s.colosseumCosts(tx, 3000)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if during.Battles != 23 || len(during.Costumes) != 23 {
|
||||
t.Fatalf("season 47 tally counted ineligible or other-season battles: %+v", during)
|
||||
}
|
||||
want := map[uint64][2]uint64{102: {3, 1}, 101: {1, 2}, 103: {1, 3}, 200: {1, 4}, 201: {1, 5}, 202: {1, 6}, 216: {1, 20}, 217: {1, 21}}
|
||||
for _, row := range during.Costumes {
|
||||
if expected, checked := want[row.ID]; checked && (row.Count != expected[0] || row.Rank != expected[1]) {
|
||||
t.Fatalf("costume %d count/rank %d/%d, want %v", row.ID, row.Count, row.Rank, expected)
|
||||
}
|
||||
}
|
||||
defaults := s.pvpDesign.Colosseum
|
||||
for costume, cost := range map[uint64]uint64{102: 50, 201: 50, 202: 45, 216: 35, 217: 30, 104: 30, 105: 30} {
|
||||
if got := during.cost(defaults, costume); got != cost {
|
||||
t.Fatalf("costume %d costs %d, want %d", costume, got, cost)
|
||||
}
|
||||
}
|
||||
if after.Battles != 1 || len(after.Costumes) != 1 || after.Costumes[0].ID != 106 {
|
||||
t.Fatalf("season 48 did not become the previous season: %+v", after)
|
||||
}
|
||||
|
||||
_, body, err := s.popularInfo(command.Context{}, "/PopularCostumeInfo", wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 6), time.UnixMilli(2500))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rows, totals [][]byte
|
||||
if err := wire.Walk(body, func(f wire.Field) error {
|
||||
switch f.Number {
|
||||
case 1:
|
||||
rows = append(rows, f.Value)
|
||||
case 2:
|
||||
totals = append(totals, f.Value)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
field := func(raw []byte, number int) uint64 {
|
||||
v, _, _ := wire.Varint(raw, number)
|
||||
return v
|
||||
}
|
||||
if len(rows) != 23 || len(totals) != 1 || field(totals[0], 2) != 23 || field(rows[0], 1) != 102 || field(rows[0], 2) != 3 || field(rows[0], 5) != 1 || field(rows[0], 6) != 50 {
|
||||
t.Fatalf("PCC_COLOSSEUM response: %x", body)
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ func seedGuildQualification(t *testing.T, owner *playerInstance) {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
c := command.Context{Identity: command.Identity{AccountID: owner.accountID}, State: tx}
|
||||
c := command.Context{Identity: command.Identity{AccountID: owner.accountID}, State: tx, InstanceIDs: owner.factory.instanceIDs()}
|
||||
rule := owner.factory.design.guild.Open
|
||||
grant := owner.factory.design.guild.Guild.CreateCost
|
||||
grant.Count *= 4
|
||||
@@ -578,6 +578,38 @@ func (g *guildGameplay) ownedPVPDeck() ([]byte, uint64) {
|
||||
}
|
||||
func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
// Mirror seasons are calendar-driven and may be between rotations. Use an
|
||||
// already-active season when the captured calendar has one; otherwise keep
|
||||
// a single Mirror season and move its window to now so it cannot overlap.
|
||||
now := time.Now()
|
||||
nowMS := uint64(now.UnixMilli())
|
||||
active := false
|
||||
var kept pvp.Season
|
||||
found := false
|
||||
seasons := make([]pvp.Season, 0, len(factory.design.pvp.Seasons))
|
||||
for _, season := range factory.design.pvp.Seasons {
|
||||
if season.Mode != pvp.Mirror {
|
||||
seasons = append(seasons, season)
|
||||
continue
|
||||
}
|
||||
active = active || season.Start <= nowMS && nowMS < season.End
|
||||
kept, found = season, true
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("GameData has no Mirror season")
|
||||
}
|
||||
if !active {
|
||||
kept.Start = nowMS - uint64(time.Hour/time.Millisecond)
|
||||
kept.End = nowMS + uint64(time.Hour/time.Millisecond)
|
||||
kept.CalculateEnd = kept.End + factory.options.calendars.RegularService.CalculateMilliseconds
|
||||
seasons = append(seasons, kept)
|
||||
factory.design.pvp.Seasons = seasons
|
||||
rules, err := pvp.NewRules(factory.design.pvp.Design, factory.design.pvp.Seasons, factory.design.pvp.Policy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.design.pvp = rules
|
||||
}
|
||||
state, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -375,7 +375,7 @@ func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte
|
||||
if s.statistics == nil {
|
||||
return code, nil, fmt.Errorf("missing popularity design")
|
||||
}
|
||||
if path == "/PopularCostumeInfo" && (v[2] > 5 || v[3] > 1 || v[4] > 4) {
|
||||
if path == "/PopularCostumeInfo" && (v[2] > 6 || v[3] > 1 || v[4] > 4) {
|
||||
return code, nil, fmt.Errorf("invalid popularity filter")
|
||||
}
|
||||
if path == "/PopularEquipInfo" {
|
||||
@@ -393,6 +393,11 @@ func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte
|
||||
}
|
||||
var body []byte
|
||||
e = s.store.View(cancel, func(tx *shared.Tx) error {
|
||||
if path == "/PopularCostumeInfo" && v[2] == 6 {
|
||||
table, e := s.colosseumCosts(tx, uint64(now.UnixMilli()))
|
||||
body = colosseumPopularityBody(table)
|
||||
return e
|
||||
}
|
||||
if path == "/PopularEquipInfo" {
|
||||
prefix := fmt.Sprintf("equip:%010d:", v[2])
|
||||
type winner struct{ id, count uint64 }
|
||||
|
||||
@@ -47,6 +47,11 @@ func (s *sharedRuntime) consumePVP(ctx context.Context, event outbox.Pending) er
|
||||
if e := json.Unmarshal(event.Envelope.Event.Payload, &battle); e != nil {
|
||||
return e
|
||||
}
|
||||
if battle.Mode == pvp.Colosseum {
|
||||
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
|
||||
return s.applyColosseumPopularity(tx, battle)
|
||||
})
|
||||
}
|
||||
if battle.Mode != pvp.Mirror {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/delivery"
|
||||
@@ -26,6 +27,8 @@ type sharedRuntime struct {
|
||||
rooms *roomResults
|
||||
store *shared.Store
|
||||
pvp *ranking.PVP
|
||||
pvpDesign *gamedata.PvpDesign
|
||||
pvpSeasons []pvp.Season
|
||||
huntRanks *ranking.MonsterHunt
|
||||
castleRanks *ranking.Castle
|
||||
rogueRanks *ranking.RogueLike
|
||||
@@ -78,7 +81,7 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
|
||||
return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, pvpDesign: design.pvp.Design, pvpSeasons: design.pvp.Seasons, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) wake(account string) {
|
||||
|
||||
@@ -49,7 +49,7 @@ func newSkyWayPlayerScenario(t *testing.T) *skyWayPlayerScenario {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()}
|
||||
for _, character := range owner.assembly.worldService.CharacterService().RawAll() {
|
||||
costume, owned := owner.assembly.collection.CostumeByIndex(character.UseCostume)
|
||||
if !owned || costume.UseChar != character.InvenIndex || character.HP == 0 {
|
||||
@@ -157,7 +157,7 @@ func (s *skyWayPlayerScenario) assets(t *testing.T) skyWayAssets {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()}
|
||||
free, bonus, err := s.owner.assembly.huntingService.HuntingAP(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
|
||||
// This encodes the 2.36.7 client's RecordData.Serialize/Compress format,
|
||||
// independently of the server parser: click events on prestige illustration
|
||||
// 1065193, point 1/1, tool 0 from GameData 20261012190548.
|
||||
// 1065193, point 1/1, tool 0 from GameData 20261021182514.
|
||||
func nativeInteractionRecording(t *testing.T, delays ...int32) []byte {
|
||||
t.Helper()
|
||||
raw := binary.LittleEndian.AppendUint32(nil, uint32(len(delays)))
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/mail"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// PackTable's missed field-card rewards include currencies in UserDBInfo,
|
||||
// ordinary content tickets and AvatarMotion ownership. MailOpen must apply
|
||||
// all three domains together and retain its one-claim receipt after restart.
|
||||
func TestPackRewardCompensationMailClaimsAllRewardDomainsOnce(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
goldBefore := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
beforeUser, _, err := wire.Bytes(g.call("/LoginUser", nil), 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spool := filepath.Join(t.TempDir(), "grants.json")
|
||||
grant := mail.Grant{AccountID: g.account, Identity: "pack-reward-compensation", Title: "Card rewards", Body: "Previously missed card rewards", SentAt: time.Now().UnixMilli(), Rewards: []mail.GrantReward{
|
||||
{Type: 4, Count: 2000}, {Type: 15, Count: 10}, {Type: 16, Count: 100}, {Type: 18, Count: 50},
|
||||
{Type: 19, ID: 3009, Count: 1}, {Type: 19, ID: 3012, Count: 1}, {Type: 50, ID: 1, Count: 1},
|
||||
}}
|
||||
if err := mail.AppendGrant(spool, grant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g.factory.options.mailGrantSpool = spool
|
||||
g.reopen()
|
||||
mailbox := g.call("/MailInfo", nil)
|
||||
var id uint64
|
||||
for _, entry := range appRows(mailbox, 1) {
|
||||
title, _, err := wire.Bytes(entry, 5)
|
||||
if err == nil && string(title) == grant.Title {
|
||||
id = appValue(entry, 1)
|
||||
}
|
||||
}
|
||||
if id == 0 {
|
||||
t.Fatal("targeted compensation did not appear in the normal mailbox")
|
||||
}
|
||||
userAfterIssue, _, err := wire.Bytes(g.call("/LoginUser", nil), 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore {
|
||||
t.Fatal("mail creation granted gold before claim")
|
||||
}
|
||||
for _, field := range []int{16, 17, 18} {
|
||||
if appValue(userAfterIssue, field) != appValue(beforeUser, field) {
|
||||
t.Fatalf("mail creation granted currency field %d before claim", field)
|
||||
}
|
||||
}
|
||||
for _, reward := range grant.Rewards[4:] {
|
||||
if got := g.itemCount(reward.Type, reward.ID); got != 0 {
|
||||
t.Fatalf("mail creation granted attachment before claim: %v count=%d", reward, got)
|
||||
}
|
||||
}
|
||||
g.call("/MailOpen", wire.AppendVarint(nil, 2, id))
|
||||
check := func() {
|
||||
t.Helper()
|
||||
if got := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold; got != goldBefore+2000 {
|
||||
t.Fatalf("gold changed incorrectly after claim/retry: %d", got)
|
||||
}
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
balances, balanceErr := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx})
|
||||
_ = tx.Rollback()
|
||||
if balanceErr != nil {
|
||||
t.Fatal(balanceErr)
|
||||
}
|
||||
for _, currency := range []struct {
|
||||
field int
|
||||
amount uint64
|
||||
}{{16, 10}, {17, 100}, {18, 50}} {
|
||||
if got := balances[currency.field]; got != appValue(beforeUser, currency.field)+currency.amount {
|
||||
t.Fatalf("currency field %d: got %d", currency.field, got)
|
||||
}
|
||||
}
|
||||
for _, reward := range grant.Rewards[4:] {
|
||||
if got := g.itemCount(reward.Type, reward.ID); got != 1 {
|
||||
t.Fatalf("attachment missing or duplicated after claim/retry: %v count=%d", reward, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
check()
|
||||
g.reopen()
|
||||
g.call("/MailInfo", nil)
|
||||
g.call("/MailOpen", wire.AppendVarint(nil, 2, id))
|
||||
check()
|
||||
}
|
||||
|
||||
func avatarChoiceRequest(shop uint64) []byte {
|
||||
price := wire.AppendVarint(wire.AppendVarint(nil, 3, 44), 4, 1000)
|
||||
return wire.AppendBytes(nil, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, shop), 2, price))
|
||||
}
|
||||
|
||||
// AvatarSelectUI -> SendFirstBuyAvatarCharRequest submits shop1's nominal
|
||||
// price without a funds check. AvatarPacket first clamps the local debit to
|
||||
// zero, then adds the response bundle. First choice is free by server policy.
|
||||
func TestSquareFirstChoiceWorksWithoutFundsAndKeepsClientBalanceConsistent(t *testing.T) {
|
||||
for _, initial := range []uint64{0, 500, 2500} {
|
||||
t.Run(fmt.Sprint(initial), func(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
if initial > 0 {
|
||||
profileGrant(g, gamedata.Reward{Type: 44, Count: initial})
|
||||
}
|
||||
before := g.wordCurrency()
|
||||
response := g.call("/AvatarShopBuy", avatarChoiceRequest(1))
|
||||
bundle, _, err := wire.Bytes(response, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
localAfterDebit := before - min(before, uint64(1000))
|
||||
for _, item := range appRows(bundle, 1) {
|
||||
if appValue(item, 3) == 44 {
|
||||
localAfterDebit += appValue(item, 4)
|
||||
}
|
||||
}
|
||||
if localAfterDebit != before || g.wordCurrency() != before {
|
||||
t.Fatalf("free choice desynchronized native/server currency: native=%d server=%d before=%d", localAfterDebit, g.wordCurrency(), before)
|
||||
}
|
||||
for _, asset := range [][2]uint64{{61, 1}, {49, 10001}, {49, 20001}, {49, 40001}, {19, 3010}, {19, 3011}} {
|
||||
if g.itemCount(asset[0], asset[1]) != 1 {
|
||||
t.Fatalf("first choice failed to deliver avatar or SquareDefault unlock %v", asset)
|
||||
}
|
||||
}
|
||||
use := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 10001), 3, 20001), 5, 40001)
|
||||
g.call("/AvatarSave", wire.AppendBytes(nil, 2, use))
|
||||
g.reopen()
|
||||
avatar := g.call("/AvatarInfo", nil)
|
||||
current, _, err := wire.Bytes(avatar, 1)
|
||||
if err != nil || appValue(current, 1) != 1 || appValue(current, 5) != 40001 {
|
||||
t.Fatalf("equipped initial avatar did not survive reopening: %v", err)
|
||||
}
|
||||
login := g.call("/LoginUser", nil)
|
||||
user, _, err := wire.Bytes(login, 1)
|
||||
if err != nil || appValue(user, 56) != 1 {
|
||||
t.Fatalf("login lost consumed first-choice eligibility: %v", err)
|
||||
}
|
||||
if before < 1000 {
|
||||
g.execute(g.request("/AvatarShopBuy", avatarChoiceRequest(2)), true)
|
||||
if g.itemCount(61, 2) != 0 || g.wordCurrency() != before {
|
||||
t.Fatal("second character bypassed ordinary purchase price")
|
||||
}
|
||||
} else {
|
||||
g.call("/AvatarShopBuy", avatarChoiceRequest(2))
|
||||
if g.itemCount(61, 2) != 1 || g.wordCurrency() != before-1000 {
|
||||
t.Fatal("second character was not charged at the authored price")
|
||||
}
|
||||
}
|
||||
if g.itemCount(19, 3010) != 1 || g.itemCount(19, 3011) != 1 {
|
||||
t.Fatal("later purchase duplicated setup unlocks")
|
||||
}
|
||||
// CommonPacket.EnterPack uses the shared card endpoints for both
|
||||
// Fishing(12) and Life(13), after their domain initialization calls.
|
||||
for _, entry := range []struct {
|
||||
id uint64
|
||||
info string
|
||||
}{{3010, "/FishingInfo"}, {3011, "/LifeInfo"}} {
|
||||
fields := wire.AppendVarint(nil, 2, entry.id)
|
||||
g.call("/PackPreviewInfo", fields)
|
||||
g.call(entry.info, nil)
|
||||
g.call("/PackInGameInfo", fields)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedInitialAvatarBatchDoesNotConsumeTheFreeChoice(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
profileGrant(g, gamedata.Reward{Type: 44, Count: 500})
|
||||
buy := g.request("/AvatarShopBuy", avatarChoiceRequest(1))
|
||||
unowned := wire.AppendBytes(nil, 2, wire.AppendVarint(nil, 1, 18))
|
||||
invalid := g.request("/AvatarSave", unowned)
|
||||
buy.Requests = append(buy.Requests, invalid.Requests...)
|
||||
g.execute(buy, true)
|
||||
g.reopen()
|
||||
if g.wordCurrency() != 500 || g.itemCount(61, 1) != 0 || g.itemCount(19, 3010) != 0 || g.itemCount(19, 3011) != 0 {
|
||||
t.Fatal("rejected initial setup retained some purchase/entitlement state")
|
||||
}
|
||||
g.call("/AvatarShopBuy", avatarChoiceRequest(2))
|
||||
if g.wordCurrency() != 500 || g.itemCount(61, 2) != 1 || g.itemCount(19, 3010) != 1 || g.itemCount(19, 3011) != 1 {
|
||||
t.Fatal("rolled-back setup consumed the one free choice")
|
||||
}
|
||||
}
|
||||
|
||||
// Pack3009 BuyRewardType/Id/Count and RandomBox930000 -> RewardGroup930000
|
||||
// supply ticket3009 plus all32 authored motions. Opening/previewing a card is
|
||||
// not a purchase; purchase receipts must survive reopening without regranting.
|
||||
func TestSquareCardPurchaseDeliversItsAuthoredRewardsOnce(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
profileGrant(g, gamedata.Reward{Type: 19, ID: 11, Count: 1})
|
||||
request := wire.AppendVarint(nil, 2, 3009)
|
||||
before := g.itemCount(19, 3009)
|
||||
g.call("/PackPreviewInfo", request)
|
||||
if g.itemCount(19, 3009) != before {
|
||||
t.Fatal("card preview granted purchase rewards")
|
||||
}
|
||||
response := g.call("/PackBuy", request)
|
||||
info, _, err := wire.Bytes(response, 1)
|
||||
if err != nil || appValue(info, 1) != 3009 || appValue(info, 8) != 1 {
|
||||
t.Fatalf("purchase did not mark the plaza card as owned: %v", err)
|
||||
}
|
||||
if g.itemCount(19, 3009) != before+1 {
|
||||
t.Fatal("plaza purchase omitted its content ticket")
|
||||
}
|
||||
var motions []uint64
|
||||
for id := uint64(1); id <= 17; id++ {
|
||||
motions = append(motions, id)
|
||||
}
|
||||
for id := uint64(100001); id <= 100015; id++ {
|
||||
motions = append(motions, id)
|
||||
}
|
||||
for _, id := range motions {
|
||||
if g.itemCount(50, id) != 1 {
|
||||
t.Fatalf("authored plaza entry motion %d not granted", id)
|
||||
}
|
||||
}
|
||||
g.reopen()
|
||||
g.call("/PackBuy", request)
|
||||
g.call("/PackInGameInfo", request)
|
||||
for _, id := range motions {
|
||||
if g.itemCount(50, id) != 1 {
|
||||
t.Fatalf("reopening/reentry duplicated motion %d", id)
|
||||
}
|
||||
}
|
||||
if g.itemCount(19, 3009) != before+1 {
|
||||
t.Fatal("reopening/reentry duplicated plaza ticket")
|
||||
}
|
||||
}
|
||||
|
||||
// GameData 20261021182514 Pack3006 is PackGuildRaid (8), with maps30061+
|
||||
// and a one-time purchase reward of 1000 gold. CommonPacket buys it through
|
||||
// the same PackBuy callback as other field cards before GuildRaid entry.
|
||||
func TestGuildRaidCardPurchasePersistsAndCannotRepeatItsReward(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
request := wire.AppendVarint(nil, 2, 3006)
|
||||
// Exercise the domain transaction without the login observer purchasing
|
||||
// unrelated open cards and adding their gold to the same command.
|
||||
call := func(path string, body []byte) []byte {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: g.account}, State: tx, InstanceIDs: g.factory.instanceIDs()}
|
||||
_, response, handled, err := g.owner.assembly.worldService.Handle(ctx, path, append(wire.AppendVarint(nil, 1, 1), body...))
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("%s: handled=%v error=%v", path, handled, err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
goldBefore := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
response := call("/PackBuy", request)
|
||||
info, _, err := wire.Bytes(response, 1)
|
||||
if err != nil || appValue(info, 1) != 3006 || appValue(info, 8) != 1 {
|
||||
t.Fatalf("guild raid card purchase did not return owned card: %v", err)
|
||||
}
|
||||
bundle, _, err := wire.Bytes(response, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var gold uint64
|
||||
for _, item := range appRows(bundle, 1) {
|
||||
if appValue(item, 3) == 4 {
|
||||
gold += appValue(item, 4)
|
||||
}
|
||||
}
|
||||
if gold != 1000 {
|
||||
t.Fatalf("guild raid card purchase omitted authored gold reward: %d", gold)
|
||||
}
|
||||
if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+1000 {
|
||||
t.Fatal("guild raid purchase returned gold without crediting the wallet")
|
||||
}
|
||||
g.reopen()
|
||||
call("/PackBuy", request)
|
||||
call("/PackPreviewInfo", request)
|
||||
if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+1000 {
|
||||
t.Fatal("reopening or previewing guild raid card repeated its purchase reward")
|
||||
}
|
||||
var owned bool
|
||||
for _, row := range appRows(call("/PackInfo", nil), 1) {
|
||||
if appValue(row, 1) == 3006 && appValue(row, 8) == 1 {
|
||||
owned = true
|
||||
}
|
||||
}
|
||||
if !owned {
|
||||
t.Fatal("guild raid card ownership lost after reopening")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/startergift"
|
||||
)
|
||||
|
||||
func TestStarterGiftCurrentSourcesExcludeDefaultsAndAchievements(t *testing.T) {
|
||||
factory, _ := newIntegrationFactory(t)
|
||||
gifts, err := factory.seeds.starterGifts.Resolve(startergift.Selection{
|
||||
Limited: factory.design.limitedCostumes, Prestige: factory.design.prestigeCatalog,
|
||||
Avatars: factory.design.avatarProfile, OwnedPrestige: map[uint64]bool{65193: true},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var external, linked []gamedata.Reward
|
||||
for _, gift := range gifts {
|
||||
switch gift.Identity {
|
||||
case startergift.LimitedAvatars:
|
||||
external = gift.Rewards
|
||||
case "starter:prestige-avatar:65193:v1":
|
||||
linked = gift.Rewards
|
||||
}
|
||||
}
|
||||
// Current AvatarItemTable unlock texts: April Fools dice, Valentine roulette,
|
||||
// artbook code, and coffee-truck voucher. None is a default or title reward.
|
||||
want := []gamedata.Reward{{Type: 49, ID: 20018, Count: 1}, {Type: 49, ID: 50007, Count: 1}, {Type: 49, ID: 60015, Count: 1}, {Type: 49, ID: 60018, Count: 1}}
|
||||
if !slices.Equal(external, want) {
|
||||
t.Fatalf("external gift=%v, want only audited external sources %v", external, want)
|
||||
}
|
||||
// AvatarSetTable 2001 links PrestigeSkin 65193 to these three pieces.
|
||||
want = []gamedata.Reward{{Type: 49, ID: 10025, Count: 1}, {Type: 49, ID: 20033, Count: 1}, {Type: 49, ID: 40048, Count: 1}}
|
||||
if !slices.Equal(linked, want) {
|
||||
t.Fatalf("owned prestige attachment=%v want %v", linked, want)
|
||||
}
|
||||
for _, gift := range gifts {
|
||||
if startergift.IsAvatarGift(gift.Identity) && gift.Identity != startergift.LimitedAvatars && gift.Identity != "starter:prestige-avatar:65193:v1" {
|
||||
t.Fatalf("unowned prestige skin received an outfit: %s", gift.Identity)
|
||||
}
|
||||
for _, reward := range gift.Rewards {
|
||||
if startergift.IsAvatarGift(gift.Identity) && (reward.Type != 49 || slices.Contains([]uint64{10001, 40001, 50013, 50014, 10030, 40055}, reward.ID)) {
|
||||
t.Fatalf("default, collaboration body, or title reward was included: %v", reward)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
current := factory.seeds.starterGifts
|
||||
legacy, err := cloneSeed(¤t)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := range legacy.Gifts {
|
||||
legacy.Gifts[i].Parts = nil
|
||||
}
|
||||
factory.seeds.starterGifts = *legacy
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
readMail := func() (map[string]uint64, map[string][]byte) {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ids := map[string]uint64{}
|
||||
records := map[string][]byte{}
|
||||
for _, bucket := range []string{"issued", "dynamic", "history"} {
|
||||
rows, err := g.owner.assembly.scope.ListEntries(tx, "mail", bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, raw := range rows {
|
||||
records[bucket+":"+key] = append([]byte(nil), raw...)
|
||||
if bucket == "issued" {
|
||||
var id uint64
|
||||
if err := json.Unmarshal(raw, &id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids[key] = id
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids, records
|
||||
}
|
||||
ids, _ := readMail()
|
||||
if ids[startergift.LimitedCostumes] == 0 || ids[startergift.PrestigeSkins] == 0 || ids[startergift.LimitedAvatars] != 0 {
|
||||
t.Fatal("old account fixture must have only the two historical gifts")
|
||||
}
|
||||
// Leave the limited costume gift unclaimed and claim the prestige gift.
|
||||
g.call("/MailOpen", appScalar(2, ids[startergift.PrestigeSkins]))
|
||||
_, before := readMail()
|
||||
factory.seeds.starterGifts = current
|
||||
g.reopen()
|
||||
g.call("/MailInfo", nil)
|
||||
ids, after := readMail()
|
||||
for key, raw := range before {
|
||||
if !bytes.Equal(raw, after[key]) {
|
||||
t.Fatalf("upgrading the gift catalog changed historical %s", key)
|
||||
}
|
||||
}
|
||||
accessoryMail := ids[startergift.LimitedAvatars]
|
||||
if accessoryMail == 0 {
|
||||
t.Fatal("existing account did not receive the new external accessory gift")
|
||||
}
|
||||
// This piece is acquired after delivery; claiming must omit its new-item row.
|
||||
scenario := &trapPlayerScenario{factory: factory, owner: g.owner, account: accounts[0]}
|
||||
scenario.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if _, err := p.eventEconomy.Apply(ctx, "other-accessory-source", nil, []gamedata.Reward{{Type: 49, ID: 20018, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
request := g.request("/MailOpen", appScalar(2, accessoryMail))
|
||||
claim := g.execute(request, false)
|
||||
if retry := g.execute(request, false); !bytes.Equal(retry, claim) {
|
||||
t.Fatal("same-request retry changed the filtered acquisition bundle")
|
||||
}
|
||||
for _, bundle := range appRows(claim, 1) {
|
||||
for _, row := range appRows(bundle, 1) {
|
||||
if appValue(row, 3) == 49 && appValue(row, 2) == 20018 {
|
||||
t.Fatal("already-owned accessory was returned as newly acquired")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, id := range []uint64{20018, 50007, 60015, 60018} {
|
||||
if g.itemCount(49, id) != 1 {
|
||||
t.Fatalf("external accessory %d was missing or duplicated", id)
|
||||
}
|
||||
}
|
||||
reopenedClaim := g.call("/MailOpen", appScalar(2, accessoryMail))
|
||||
for _, bundle := range appRows(reopenedClaim, 1) {
|
||||
if len(bundle) != 0 {
|
||||
t.Fatal("a new request to an opened accessory mail returned an acquisition bundle")
|
||||
}
|
||||
}
|
||||
for _, id := range []uint64{20018, 50007, 60015, 60018} {
|
||||
if g.itemCount(49, id) != 1 {
|
||||
t.Fatalf("new claim request duplicated external accessory %d", id)
|
||||
}
|
||||
}
|
||||
_, stable := readMail()
|
||||
g.reopen()
|
||||
g.call("/MailInfo", nil)
|
||||
_, reopened := readMail()
|
||||
if len(stable) != len(reopened) {
|
||||
t.Fatal("relogin issued the same gifts again")
|
||||
}
|
||||
for key, raw := range stable {
|
||||
if !bytes.Equal(raw, reopened[key]) {
|
||||
t.Fatalf("relogin changed gift record %s", key)
|
||||
}
|
||||
}
|
||||
for _, id := range []uint64{20018, 50007, 60015, 60018} {
|
||||
if g.itemCount(49, id) != 1 {
|
||||
t.Fatalf("relogin duplicated or lost external accessory %d", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewlyOwnedPrestigeCreatesLinkedGiftOnMailInfoWithoutDuplicatingSharedPieces(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() { _ = g.owner.Close() })
|
||||
scenario := &trapPlayerScenario{factory: factory, owner: owner, account: accounts[0]}
|
||||
var linkedMail uint64
|
||||
readLinked := func() {
|
||||
t.Helper()
|
||||
scenario.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
rows, err := p.scope.ListEntries(ctx.State, "mail", "issued")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw := rows["starter:prestige-avatar:65193:v1"]; raw != nil {
|
||||
if err := json.Unmarshal(raw, &linkedMail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
readLinked()
|
||||
if linkedMail != 0 {
|
||||
t.Fatal("unowned prestige skin received an attachment gift")
|
||||
}
|
||||
scenario.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if _, err := p.eventEconomy.Apply(ctx, "new-owned-prestige", nil, []gamedata.Reward{{Type: 45, ID: 65193, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Another legitimate mail rewards one shared piece before the linked gift.
|
||||
if err := p.mailService.EnqueueCompensation(ctx, "shared-piece-source", "Shared piece", "Another source of the same piece", []gamedata.Reward{{Type: 49, ID: 10025, Count: 1}}, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
g.call("/MailInfo", nil)
|
||||
readLinked()
|
||||
if linkedMail == 0 {
|
||||
t.Fatal("new ownership did not produce its linked outfit in the current session")
|
||||
}
|
||||
var sharedMail uint64
|
||||
scenario.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
rows, err := p.scope.ListEntries(ctx.State, "mail", "issued")
|
||||
if err != nil || json.Unmarshal(rows["shared-piece-source"], &sharedMail) != nil {
|
||||
t.Fatal("shared-piece source mail missing", err)
|
||||
}
|
||||
})
|
||||
g.call("/MailOpen", appScalar(2, sharedMail))
|
||||
claim := g.call("/MailOpen", appScalar(2, linkedMail))
|
||||
var newlyAcquired []uint64
|
||||
for _, bundle := range appRows(claim, 1) {
|
||||
for _, row := range appRows(bundle, 1) {
|
||||
if appValue(row, 3) == 49 {
|
||||
newlyAcquired = append(newlyAcquired, appValue(row, 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(newlyAcquired)
|
||||
if !slices.Equal(newlyAcquired, []uint64{20033, 40048}) {
|
||||
t.Fatalf("linked gift returned unexpected new pieces: %v", newlyAcquired)
|
||||
}
|
||||
for _, id := range []uint64{10025, 20033, 40048} {
|
||||
if g.itemCount(49, id) != 1 {
|
||||
t.Fatalf("linked piece %d duplicated or missing", id)
|
||||
}
|
||||
}
|
||||
if g.itemCount(61, 15) != 0 || g.itemCount(49, 10023) != 0 || g.itemCount(49, 50013) != 0 {
|
||||
t.Fatal("linked prestige gift granted a default avatar, default outfit, or title reward")
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,7 @@ func TestUserContentsInfoReflectsCommittedProfileAndRejectsOtherOwners(t *testin
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := action(command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-combat"}, State: tx}); err != nil {
|
||||
if _, err := action(command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-combat"}, State: tx, InstanceIDs: factory.instanceIDs()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
|
||||
@@ -23,7 +23,11 @@ type CashProductDesign struct {
|
||||
}
|
||||
type CashShopDesign struct{ GroupID, ID, ProductGroupID, BulkOrderShow uint64 }
|
||||
type EventShopDesign struct{ ID, ProductGroupID uint64 }
|
||||
type CashPackageDesign struct{ GroupID, ID, SaleGroup, PackageType, PaidShopGroupID, PaidShopID, ContentsGroupID, ContentsSortID uint64 }
|
||||
type CashPackageDesign struct {
|
||||
GroupID, ID, SaleGroup, PackageType, PaidShopGroupID, PaidShopID, ContentsGroupID, ContentsSortID uint64
|
||||
ResourceName string
|
||||
Sequential bool
|
||||
}
|
||||
type CashCatalog struct {
|
||||
Products []CashProductDesign
|
||||
Shops []CashShopDesign
|
||||
@@ -111,7 +115,15 @@ func loadCashCatalog(db *sql.DB) (*CashCatalog, error) {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
c.Packages = append(c.Packages, CashPackageDesign{v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]})
|
||||
resource, _, e := wire.Bytes(raw, 16)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
c.Packages = append(c.Packages, CashPackageDesign{
|
||||
GroupID: v[0], ID: v[1], SaleGroup: v[2], PackageType: v[3],
|
||||
PaidShopGroupID: v[4], PaidShopID: v[5], ContentsGroupID: v[6], ContentsSortID: v[7],
|
||||
ResourceName: string(resource),
|
||||
})
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -6,10 +6,12 @@ import (
|
||||
)
|
||||
|
||||
// ContentOpeningDesign describes the rapport prologue's prerequisite and
|
||||
// completion marker. The client maps ContentOpenRequest type 1 to group 23,
|
||||
// detail 2; ticket identities and level requirements remain version data.
|
||||
// completion marker, and the dating unlock. The client maps ContentOpenRequest
|
||||
// type 1 to group 23, detail 2, and checks Define_ContentOpenType
|
||||
// ContentUnlockDating (group 19, detail 1) before granting the cafeteria
|
||||
// introduction; ticket identities and level requirements remain version data.
|
||||
type ContentOpeningDesign struct {
|
||||
Prerequisite, Completion ContentOpenRule
|
||||
Prerequisite, Completion, Dating ContentOpenRule
|
||||
}
|
||||
|
||||
func LoadContentOpeningDesign(root, version string) (*ContentOpeningDesign, error) {
|
||||
@@ -83,13 +85,20 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) {
|
||||
return nil, fmt.Errorf("gamedata: invalid content opening %d/%d identity or ticket", group, id)
|
||||
}
|
||||
seen[key] = true
|
||||
rule := ContentOpenRule{TutorialID: values[3], SquadLevel: values[4], TicketID: ticket}
|
||||
if key == [2]uint64{19, 1} {
|
||||
if tickets[ticket] != 1 {
|
||||
return nil, fmt.Errorf("gamedata: dating opening requires permanent content ticket")
|
||||
}
|
||||
d.Dating = rule
|
||||
continue
|
||||
}
|
||||
if group != 23 || (id != 1 && id != 2) {
|
||||
continue
|
||||
}
|
||||
if tickets[ticket] != 1 {
|
||||
return nil, fmt.Errorf("gamedata: rapport opening %d requires permanent content ticket", id)
|
||||
}
|
||||
rule := ContentOpenRule{TutorialID: values[3], SquadLevel: values[4], TicketID: ticket}
|
||||
if id == 1 {
|
||||
d.Prerequisite = rule
|
||||
} else {
|
||||
@@ -99,6 +108,9 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) {
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !seen[[2]uint64{19, 1}] {
|
||||
return nil, fmt.Errorf("gamedata: missing dating opening rule")
|
||||
}
|
||||
if !seen[[2]uint64{23, 1}] || !seen[[2]uint64{23, 2}] || d.Prerequisite.TicketID == d.Completion.TicketID {
|
||||
return nil, fmt.Errorf("gamedata: missing or indistinguishable rapport opening rules")
|
||||
}
|
||||
|
||||
@@ -21,14 +21,15 @@ type EquipmentGachaCatalog struct {
|
||||
equipment map[uint64]EquipmentDesign
|
||||
}
|
||||
type EquipmentGacha struct {
|
||||
ID uint64
|
||||
Count int
|
||||
FreeCountDay uint64
|
||||
PriceType, Price uint64
|
||||
TicketIDs []uint64
|
||||
Pool []WeightedEquipment
|
||||
TicketOnly bool
|
||||
Grades map[uint64]uint64
|
||||
ID uint64
|
||||
Count int
|
||||
FreeCountDay uint64
|
||||
DailyPayGachaCount, DailyPayGachaPriceCount uint64
|
||||
PriceType, Price uint64
|
||||
TicketIDs []uint64
|
||||
Pool []WeightedEquipment
|
||||
TicketOnly bool
|
||||
Grades map[uint64]uint64
|
||||
}
|
||||
type EquipmentGachaGroup struct {
|
||||
ID, FixedID, PointCount, OneTimeGachaID, TenTimeGachaID uint64
|
||||
@@ -280,6 +281,14 @@ func loadEquipmentGacha(db *sql.DB, id uint64) (EquipmentGacha, error) {
|
||||
if len(freeCounts) == 1 {
|
||||
freeCount = freeCounts[0]
|
||||
}
|
||||
dailyPayCount, err := optionalScalar(raw, 1)
|
||||
if err != nil {
|
||||
return EquipmentGacha{}, fmt.Errorf("gamedata: equipment paid allowance %d: %w", id, err)
|
||||
}
|
||||
dailyPayPrice, err := optionalScalar(raw, 2)
|
||||
if err != nil || (dailyPayCount == 0) != (dailyPayPrice == 0) {
|
||||
return EquipmentGacha{}, fmt.Errorf("gamedata: malformed equipment paid discount %d", id)
|
||||
}
|
||||
// Partial ticket consumption bills remaining draws individually; the local
|
||||
// billing path currently requires an integral price per draw.
|
||||
if len(count) != 1 || len(reward) != 1 || len(price) != 1 || len(kind) != 1 || kind[0] != 3 || count[0] == 0 || price[0] == 0 || price[0]%count[0] != 0 {
|
||||
@@ -289,7 +298,7 @@ func loadEquipmentGacha(db *sql.DB, id uint64) (EquipmentGacha, error) {
|
||||
if err != nil {
|
||||
return EquipmentGacha{}, fmt.Errorf("gamedata: equipment gacha %d: %w", id, err)
|
||||
}
|
||||
return EquipmentGacha{ID: id, Count: int(count[0]), FreeCountDay: freeCount, PriceType: kind[0], Price: price[0], TicketIDs: append([]uint64(nil), tickets...), Pool: pool}, nil
|
||||
return EquipmentGacha{ID: id, Count: int(count[0]), FreeCountDay: freeCount, DailyPayGachaCount: dailyPayCount, DailyPayGachaPriceCount: dailyPayPrice, PriceType: kind[0], Price: price[0], TicketIDs: append([]uint64(nil), tickets...), Pool: pool}, nil
|
||||
}
|
||||
func loadEquipmentRewardPool(db *sql.DB, groupID uint64) ([]WeightedEquipment, error) {
|
||||
var raw []byte
|
||||
|
||||
@@ -17,9 +17,9 @@ type EventMissionGroup struct {
|
||||
Groups []uint64
|
||||
}
|
||||
type EventTask struct {
|
||||
ID, Group, Type, SubType, Target, PassExp, UnlockPack, UnlockQuest uint64
|
||||
Params []uint64
|
||||
Rewards []Reward
|
||||
ID, Group, Type, SubType, SubTypeMoreCheck, Target, PassExp, UnlockPack, UnlockQuest uint64
|
||||
Params []uint64
|
||||
Rewards []Reward
|
||||
}
|
||||
type EventPass struct {
|
||||
ID, MissionGroup, LevelGroup, Type, ScheduleType, NewbieGroup, NewbieStep uint64
|
||||
@@ -153,7 +153,7 @@ func loadEventTasksDesign(db *sql.DB) (*EventTasksDesign, error) {
|
||||
return nil
|
||||
}
|
||||
r := EventTask{}
|
||||
if e = read(p, map[int]*uint64{8: &r.ID, 6: &r.Group, 3: &r.Type, 1: &r.SubType, 4: &r.Target, 12: &r.PassExp, 19: &r.UnlockPack, 20: &r.UnlockQuest}); e != nil {
|
||||
if e = read(p, map[int]*uint64{8: &r.ID, 6: &r.Group, 3: &r.Type, 1: &r.SubType, 9: &r.SubTypeMoreCheck, 4: &r.Target, 12: &r.PassExp, 19: &r.UnlockPack, 20: &r.UnlockQuest}); e != nil {
|
||||
return e
|
||||
}
|
||||
r.Params, e = packedInts(p, 2)
|
||||
|
||||
@@ -58,7 +58,8 @@ func LoadFieldMonsterMaps(root, version string, pack int) (map[int][]int, error)
|
||||
}
|
||||
mapID, ok := maps[string(scene)]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("gamedata: monster scene without map")
|
||||
// A scene with no MapTable row is unreachable, so it places nothing.
|
||||
continue
|
||||
}
|
||||
out[int(id)] = append(out[int(id)], mapID)
|
||||
}
|
||||
|
||||
@@ -9,9 +9,12 @@ import (
|
||||
// enum; IDs and entry restrictions come from the installed GameData tables.
|
||||
type FieldPack struct {
|
||||
ID, Type, BuyPrice, UseSchedule uint64
|
||||
BuyType uint64
|
||||
BuyRewards []Reward
|
||||
TicketID, SquadLevel uint64
|
||||
HasOpenRule bool
|
||||
MapIDs map[int]bool
|
||||
IntroQuest *QuestDesign
|
||||
}
|
||||
|
||||
func LoadFieldPacks(root, version string) (map[int]FieldPack, error) {
|
||||
@@ -23,6 +26,11 @@ func LoadFieldPacks(root, version string) (map[int]FieldPack, error) {
|
||||
return loadFieldPacks(db)
|
||||
}
|
||||
|
||||
// fieldPackTypes are the Define_PackType values served as field packs: 1 Char,
|
||||
// 3 PVP, 4 EvilCastle, 5 SkyWay, 6 Event, 7 TotalWar, 8 GuildRaid, 9 Cafeteria, 10 Colosseum,
|
||||
// 11 Square, 12 Fishing, 13 Life, 14 Ib.
|
||||
var fieldPackTypes = map[uint64]bool{1: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true, 10: true, 11: true, 12: true, 13: true, 14: true}
|
||||
|
||||
func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) {
|
||||
result := map[int]FieldPack{}
|
||||
rows, err := db.Query("SELECT id,ProtoBuf FROM PackTable ORDER BY id")
|
||||
@@ -37,7 +45,7 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) {
|
||||
return nil, err
|
||||
}
|
||||
values := map[int]uint64{}
|
||||
for _, field := range []int{7, 25, 55, 65} {
|
||||
for _, field := range []int{7, 11, 25, 55, 65} {
|
||||
v, e := packedInts(raw, field)
|
||||
if e != nil || len(v) > 1 {
|
||||
_ = rows.Close()
|
||||
@@ -47,14 +55,23 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) {
|
||||
values[field] = v[0]
|
||||
}
|
||||
}
|
||||
if values[55] != 3 && values[55] != 4 && values[55] != 5 && values[55] != 7 && values[55] != 10 {
|
||||
if !fieldPackTypes[values[55]] {
|
||||
continue
|
||||
}
|
||||
if id <= 0 || values[25] != uint64(id) {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("gamedata: invalid field pack identity %d", id)
|
||||
}
|
||||
result[id] = FieldPack{ID: uint64(id), Type: values[55], BuyPrice: values[7], UseSchedule: values[65], MapIDs: map[int]bool{}}
|
||||
pack := FieldPack{ID: uint64(id), Type: values[55], BuyPrice: values[7], BuyType: values[11], UseSchedule: values[65], MapIDs: map[int]bool{}}
|
||||
rewards, err := eventGameRewards(raw, 10, 9, 8)
|
||||
if err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
for _, reward := range rewards {
|
||||
pack.BuyRewards = append(pack.BuyRewards, Reward(reward))
|
||||
}
|
||||
result[id] = pack
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
@@ -123,6 +140,41 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) {
|
||||
if len(pack.MapIDs) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: arena pack %d has no map", id)
|
||||
}
|
||||
intro, err := loadFieldIntroduction(db, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pack.IntroQuest = intro
|
||||
result[id] = pack
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Standalone field introductions have one accept movie and no quest chain,
|
||||
// completion movie or rewards. Ordinary field quest chains retain their own
|
||||
// acceptance and settlement rules, even when their first quest has a movie.
|
||||
func loadFieldIntroduction(db *sql.DB, packID int) (*QuestDesign, error) {
|
||||
var exists bool
|
||||
if err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", fmt.Sprintf("QuestTable%d", packID)).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
quests, err := loadQuestDesignDB(db, packID)
|
||||
if err != nil || len(quests) != 1 {
|
||||
return nil, err
|
||||
}
|
||||
for _, quest := range quests {
|
||||
if quest.Type != 0 || quest.PriorQuestID != 0 || quest.NextQuestID != 0 || quest.AcceptCinemaName == "" || quest.CompleteCinemaName != "" || len(quest.GiveQuestItemIDs) != 0 || len(quest.CollectionRewards) != 0 {
|
||||
return nil, nil
|
||||
}
|
||||
for _, rewards := range quest.Rewards {
|
||||
if len(rewards) != 0 {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return &quest, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
@@ -143,15 +143,16 @@ type GachaFixedRoll struct {
|
||||
}
|
||||
|
||||
type RegularGachaCatalog struct {
|
||||
Gachas map[uint64]RegularGacha
|
||||
gachaEventAddFreeCount uint64
|
||||
characters map[uint64]CharacterDesign
|
||||
groups map[uint64]GachaGroupDesign
|
||||
byGacha map[uint64]uint64
|
||||
fixed map[uint64]GachaFixedDesign
|
||||
grades map[uint64]uint64
|
||||
stepUps map[uint64]GachaStepUpDesign
|
||||
stepByGacha map[uint64]GachaStepDesign
|
||||
Gachas map[uint64]RegularGacha
|
||||
gachaEventAddFreeCount uint64
|
||||
gachaEventAddDailyPayCount uint64
|
||||
characters map[uint64]CharacterDesign
|
||||
groups map[uint64]GachaGroupDesign
|
||||
byGacha map[uint64]uint64
|
||||
fixed map[uint64]GachaFixedDesign
|
||||
grades map[uint64]uint64
|
||||
stepUps map[uint64]GachaStepUpDesign
|
||||
stepByGacha map[uint64]GachaStepDesign
|
||||
}
|
||||
|
||||
func (c *RegularGachaCatalog) GachaEventAddFreeCount() uint64 {
|
||||
@@ -161,6 +162,13 @@ func (c *RegularGachaCatalog) GachaEventAddFreeCount() uint64 {
|
||||
return c.gachaEventAddFreeCount
|
||||
}
|
||||
|
||||
func (c *RegularGachaCatalog) GachaEventAddDailyPayCount() uint64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
return c.gachaEventAddDailyPayCount
|
||||
}
|
||||
|
||||
func (c *RegularGachaCatalog) SetGachaEventAddFreeCount(count uint64) error {
|
||||
if c == nil || count > 256 {
|
||||
return errors.New("gamedata: invalid gacha event free-count bonus")
|
||||
@@ -983,6 +991,11 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
paidBonus, err := optionalScalar(defaults, 47)
|
||||
if err != nil || paidBonus > 256 {
|
||||
return nil, errors.New("gamedata: malformed GachaEventAddDailyPayGachaCount")
|
||||
}
|
||||
catalog.gachaEventAddDailyPayCount = paidBonus
|
||||
gachaIDs := make(map[uint64]struct{})
|
||||
for _, groupID := range groupIDs {
|
||||
var raw []byte
|
||||
|
||||
@@ -21,9 +21,11 @@ type GuildRaidRules struct {
|
||||
FlagVersions []GuildRaidFlagVersion
|
||||
TurnAddScore, TurnScoreValue, SupportScore float64
|
||||
DailySupporterUses, BasicSupportReward, RentalSupportReward, RewardMailID uint64
|
||||
Bosses map[uint64]map[uint64]GuildRaidBoss
|
||||
ScoreRewards []GuildRaidScoreReward
|
||||
RankRewards []GuildRaidRankReward
|
||||
// OverkillLevel 0 disables overkill, matching BattleProcessor.IsOverKillMode.
|
||||
OverkillLevel, OverkillMemberCount uint64
|
||||
Bosses map[uint64]map[uint64]GuildRaidBoss
|
||||
ScoreRewards []GuildRaidScoreReward
|
||||
RankRewards []GuildRaidRankReward
|
||||
}
|
||||
|
||||
type GuildRaidFlagVersion struct{ GroupID, MinSeason, MaxSeason uint64 }
|
||||
@@ -130,18 +132,19 @@ func LoadGuildDesign(root, version string) (*GuildDesign, error) {
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM GuildRaidDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err = cashScalars(raw, 3, 21, 22, 15)
|
||||
v, err = cashScalars(raw, 3, 23, 24, 15, 17, 18)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Raid.DailySupporterUses, d.Raid.BasicSupportReward, d.Raid.RentalSupportReward, d.Raid.RewardMailID = v[0], v[1], v[2], v[3]
|
||||
if d.Raid.TurnAddScore, err = optionalDouble(raw, 24); err != nil {
|
||||
d.Raid.OverkillLevel, d.Raid.OverkillMemberCount = v[4], v[5]
|
||||
if d.Raid.TurnAddScore, err = optionalDouble(raw, 26); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Raid.TurnScoreValue, err = optionalDouble(raw, 25); err != nil {
|
||||
if d.Raid.TurnScoreValue, err = optionalDouble(raw, 27); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Raid.SupportScore, err = optionalDouble(raw, 23); err != nil {
|
||||
if d.Raid.SupportScore, err = optionalDouble(raw, 25); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM SupportCharacterDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
|
||||
@@ -57,6 +57,16 @@ var mailItemSources = []mailItemSource{
|
||||
// directly; their reward ID is zero.
|
||||
var MailCurrencyTypes = []uint64{2, 3, 4, 12, 20}
|
||||
|
||||
// MailEconomyCurrencyTypes are the other currencies a compensation mail can
|
||||
// carry: their claim is credited by the event economy (wallet hope powder and
|
||||
// refining traces, action points and the gameplay-entry balances such as the
|
||||
// Cafeteria and decoration coins). Their reward ID is zero as well.
|
||||
var MailEconomyCurrencyTypes = []uint64{15, 16, 18, 21, 22, 23, 24, 30, 31, 32, 33, 35, 38, 39, 40, 41, 42, 43, 44, 52, 53, 54, 60, 68, 70, 72}
|
||||
|
||||
func mailCurrency(elementType uint64) bool {
|
||||
return slices.Contains(MailCurrencyTypes, elementType) || slices.Contains(MailEconomyCurrencyTypes, elementType)
|
||||
}
|
||||
|
||||
// LoadMailCatalog returns every safe direct-mail attachment in GameData.
|
||||
func LoadMailCatalog(root, version string) ([]MailCatalogItem, error) {
|
||||
var items []MailCatalogItem
|
||||
@@ -101,7 +111,7 @@ func loadMailCatalog(db *sql.DB) ([]MailCatalogItem, error) {
|
||||
if elementType == 0 {
|
||||
elementType = rowID
|
||||
}
|
||||
if slices.Contains(MailCurrencyTypes, elementType) {
|
||||
if mailCurrency(elementType) {
|
||||
items = append(items, MailCatalogItem{ElementType: elementType, Category: "currency", Name: names["NameTextTable"][singleVarint(proto, 5)]})
|
||||
}
|
||||
return nil
|
||||
@@ -154,7 +164,7 @@ func fixedRandomBoxes(db *sql.DB, items []MailCatalogItem) (map[uint64]boxReward
|
||||
if len(ids) != 1 || len(types) != 1 || len(counts) != 1 || types[0] == 0 || counts[0] == 0 {
|
||||
return nil
|
||||
}
|
||||
currency := slices.Contains(MailCurrencyTypes, types[0])
|
||||
currency := mailCurrency(types[0])
|
||||
if currency != (ids[0] == 0) {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package gamedata
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type AvatarPartRule struct{ Category, Character, Maximum uint64 }
|
||||
type AvatarPartRule struct{ Category, Character, Maximum, UnlockTextID uint64 }
|
||||
type AvatarCharacterRule struct {
|
||||
Maximum uint64
|
||||
Collaboration bool
|
||||
@@ -15,11 +18,14 @@ type AvatarProduct struct {
|
||||
Visibility, UnlockType, UnlockValue, UnlockSub uint64
|
||||
}
|
||||
type AvatarProfileDesign struct {
|
||||
Characters map[uint64]AvatarCharacterRule
|
||||
Parts map[uint64]AvatarPartRule
|
||||
MotionMaximum map[uint64]uint64
|
||||
Shop, MotionShop map[uint64]AvatarProduct
|
||||
Bundles *AvatarRewardDesign
|
||||
InitialUnlockTickets []uint64
|
||||
SquareChannels, SquareChannelCapacity uint64
|
||||
Characters map[uint64]AvatarCharacterRule
|
||||
Parts map[uint64]AvatarPartRule
|
||||
MotionMaximum map[uint64]uint64
|
||||
Shop, MotionShop map[uint64]AvatarProduct
|
||||
Bundles *AvatarRewardDesign
|
||||
PrestigeSets map[uint64][]Reward
|
||||
}
|
||||
|
||||
func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error) {
|
||||
@@ -33,6 +39,51 @@ func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.PrestigeSets = map[uint64][]Reward{}
|
||||
if err := readCashMetadata(db, "AvatarSetTable", func(raw []byte) error {
|
||||
skin, err := optionalScalar(raw, 1)
|
||||
if err != nil || skin == 0 {
|
||||
return err
|
||||
}
|
||||
id, err := optionalScalar(raw, 6)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(d.PrestigeSets[skin]) != 0 {
|
||||
return fmt.Errorf("gamedata: duplicate prestige avatar set for skin %d", skin)
|
||||
}
|
||||
for _, reward := range d.Bundles.Sets[id] {
|
||||
if reward.Type != 49 || reward.Count != 1 {
|
||||
return fmt.Errorf("gamedata: invalid prestige avatar member")
|
||||
}
|
||||
d.PrestigeSets[skin] = append(d.PrestigeSets[skin], Reward(reward))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := readCashMetadata(db, "SquareDefaultTable", func(raw []byte) error {
|
||||
channels, err := optionalScalar(raw, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
capacity, err := optionalScalar(raw, 5)
|
||||
if err != nil || channels == 0 || channels > 10000 || capacity == 0 || capacity > 1000 {
|
||||
return fmt.Errorf("gamedata: invalid square channel rules")
|
||||
}
|
||||
d.SquareChannels, d.SquareChannelCapacity = channels, capacity
|
||||
tickets, err := packedInts(raw, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if slices.Contains(tickets, uint64(0)) {
|
||||
return fmt.Errorf("gamedata: invalid avatar setup ticket")
|
||||
}
|
||||
d.InitialUnlockTickets = append(d.InitialUnlockTickets, tickets...)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = readCashMetadata(db, "AvatarCharTable", func(raw []byte) error {
|
||||
id, err := optionalScalar(raw, 6)
|
||||
if err != nil || id == 0 {
|
||||
@@ -84,7 +135,11 @@ func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Parts[id] = AvatarPartRule{category, character, maximum}
|
||||
unlockText, err := optionalScalar(raw, 8)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Parts[id] = AvatarPartRule{Category: category, Character: character, Maximum: maximum, UnlockTextID: unlockText}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -24,10 +24,28 @@ type ColosseumDefaults struct {
|
||||
HistoryHours, HistoryLimit, TicketBuyType, TicketBuyID, TicketBuyCost uint64
|
||||
MatchExclude, CandidateCount uint64
|
||||
MatchRanges []uint64
|
||||
// Costume cost brackets: popularity ranks up to CostRankBoundaries[i]
|
||||
// cost CostRankValues[i]; other costumes cost CostDefault.
|
||||
CostDefault uint64
|
||||
CostRankBoundaries [4]uint64
|
||||
CostRankValues [4]uint64
|
||||
PopularCostumeMinimumRankGroup uint64
|
||||
}
|
||||
|
||||
// CostumeCost prices a costume by its 1-based colosseum popularity rank;
|
||||
// zero means the costume was not ranked.
|
||||
func (c ColosseumDefaults) CostumeCost(rank uint64) uint64 {
|
||||
for i, boundary := range c.CostRankBoundaries {
|
||||
if rank != 0 && rank <= boundary {
|
||||
return c.CostRankValues[i]
|
||||
}
|
||||
}
|
||||
return c.CostDefault
|
||||
}
|
||||
|
||||
type ColosseumRank struct {
|
||||
Group, ID uint64
|
||||
RankGroup uint64
|
||||
TopPercent float64
|
||||
Rewards []BattleReward
|
||||
}
|
||||
@@ -161,10 +179,12 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) {
|
||||
}},
|
||||
{"ColosseumDefaultTable", func(raw []byte) error {
|
||||
m := &d.Colosseum
|
||||
if err := pvpScalars(raw, map[int]*uint64{3: &m.MinimumVP, 4: &m.TicketBuyCost, 5: &m.TicketBuyID, 6: &m.TicketBuyType, 8: &m.HistoryHours, 9: &m.HistoryLimit, 16: &m.DefaultChange, 17: &m.MaximumChange, 18: &m.MinimumChange, 19: &m.VariableChange, 22: &m.MatchExclude, 30: &m.CandidateCount}); err != nil {
|
||||
if err := pvpScalars(raw, map[int]*uint64{3: &m.MinimumVP, 4: &m.TicketBuyCost, 5: &m.TicketBuyID, 6: &m.TicketBuyType, 8: &m.HistoryHours, 9: &m.HistoryLimit, 16: &m.DefaultChange, 17: &m.MaximumChange, 18: &m.MinimumChange, 19: &m.VariableChange, 31: &m.MatchExclude, 40: &m.CandidateCount,
|
||||
20: &m.CostDefault, 21: &m.CostRankBoundaries[0], 22: &m.CostRankBoundaries[1], 23: &m.CostRankBoundaries[2], 24: &m.CostRankBoundaries[3],
|
||||
25: &m.CostRankValues[0], 26: &m.CostRankValues[1], 27: &m.CostRankValues[2], 28: &m.CostRankValues[3], 34: &m.PopularCostumeMinimumRankGroup}); err != nil {
|
||||
return err
|
||||
}
|
||||
m.MatchRanges, err = packedInts(raw, 23)
|
||||
m.MatchRanges, err = packedInts(raw, 32)
|
||||
return err
|
||||
}},
|
||||
{"ColosseumSeasonTable", func(raw []byte) error {
|
||||
@@ -200,7 +220,7 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) {
|
||||
}},
|
||||
{"ColosseumRankTable", func(raw []byte) error {
|
||||
var r ColosseumRank
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &r.Group, 3: &r.ID}); err != nil {
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &r.Group, 3: &r.ID, 4: &r.RankGroup}); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.TopPercent, err = optionalDouble(raw, 10); err != nil {
|
||||
@@ -226,7 +246,7 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if d.Mirror.StartVP == 0 || d.Mirror.TicketCost == 0 || len(d.MirrorRanks) == 0 || len(d.ColosseumRules) == 0 {
|
||||
if d.Mirror.StartVP == 0 || d.Mirror.TicketCost == 0 || len(d.MirrorRanks) == 0 || len(d.ColosseumRules) == 0 || d.Colosseum.CostDefault == 0 || d.Colosseum.PopularCostumeMinimumRankGroup == 0 {
|
||||
return nil, fmt.Errorf("gamedata: incomplete PVP design")
|
||||
}
|
||||
for group := range d.MirrorRanks {
|
||||
@@ -284,7 +304,7 @@ func (d *PvpDesign) ColosseumRule(season, kind uint64) ([]uint64, error) {
|
||||
}
|
||||
values, ok := d.ColosseumRules[group][kind]
|
||||
if !ok {
|
||||
if kind == 30 || kind == 31 {
|
||||
if kind == 30 || kind == 31 || kind == 32 {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("gamedata: missing colosseum rule %d", kind)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// LoadQuestDifficulties reads the pack-specific selectable difficulties;
|
||||
// normal (zero) is the base story chain and is absent from this table.
|
||||
// normal (zero) is the base story chain and is selectable in every listed pack.
|
||||
func LoadQuestDifficulties(root, version string) (map[int]map[int]bool, error) {
|
||||
db, release, err := OpenDatabase(root, version, "common")
|
||||
if err != nil {
|
||||
@@ -27,7 +27,7 @@ func loadQuestDifficultiesDB(db *sql.DB) (map[int]map[int]bool, error) {
|
||||
if err := rows.Scan(&pack, &level); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pack <= 0 || level < 1 || level > 4 {
|
||||
if pack <= 0 || level < 0 || level > 4 {
|
||||
return nil, fmt.Errorf("gamedata: invalid difficulty pack%d level%d", pack, level)
|
||||
}
|
||||
if result[pack] == nil {
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
type QuestDesign struct {
|
||||
ID int
|
||||
Type int
|
||||
ConditionType int
|
||||
ConditionCount int
|
||||
PriorQuestID int
|
||||
NextQuestID int
|
||||
AcceptCinemaName string
|
||||
@@ -101,7 +103,7 @@ func loadQuestDesignDB(db *sql.DB, packID int) (map[int]QuestDesign, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gamedata: quest%d give items: %w", id, err)
|
||||
}
|
||||
for field, dst := range map[int]*int{63: &entry.Type, 37: &entry.PriorQuestID, 35: &entry.NextQuestID, 62: &entry.TimelineStartMapID} {
|
||||
for field, dst := range map[int]*int{63: &entry.Type, 11: &entry.ConditionType, 10: &entry.ConditionCount, 37: &entry.PriorQuestID, 35: &entry.NextQuestID, 62: &entry.TimelineStartMapID} {
|
||||
values, err := packedInts(proto, field)
|
||||
if err != nil || len(values) > 1 || (len(values) == 1 && values[0] > uint64(^uint32(0)>>1)) {
|
||||
return nil, fmt.Errorf("gamedata: invalid quest %d field%d", id, field)
|
||||
|
||||
@@ -74,7 +74,8 @@ func LoadSpineInteractionDesign(root, version string) (*SpineInteractionDesign,
|
||||
if err := read("SpineInteractionPointTable", func(raw []byte) error {
|
||||
v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
|
||||
key := InteractionPointKey{v(8), v(5), v(6)}
|
||||
if key[0] == 0 || key[1] == 0 || key[2] == 0 {
|
||||
// GameData 20261021182514 has point 16/2/0: proto3 omits a zero point id.
|
||||
if key[0] == 0 || key[1] == 0 {
|
||||
return fmt.Errorf("gamedata: invalid interaction point")
|
||||
}
|
||||
d.Points[key] = InteractionPoint{Achievement: v(1) != 0, Connected: InteractionPointKey{key[0], v(3), v(4)}, RewardGroup: v(21), Motions: map[uint64]bool{}}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package castle
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
|
||||
// MissionProgress is the saved castle progress mission conditions derive
|
||||
// from. Pride floors include every archived season.
|
||||
type MissionProgress struct {
|
||||
// Towers maps a battle mode to its cleared tower floors.
|
||||
Towers map[uint64]map[uint64]bool
|
||||
PrideFought, PrideCleared map[uint64]bool
|
||||
TotalWarBest uint64
|
||||
}
|
||||
|
||||
// MissionProgress reads the castle save without rolling its season over.
|
||||
func (s *Service) MissionProgress(ctx command.Context) (MissionProgress, error) {
|
||||
out := MissionProgress{Towers: map[uint64]map[uint64]bool{}, PrideFought: map[uint64]bool{}, PrideCleared: map[uint64]bool{}}
|
||||
v := state{}
|
||||
raw, ok, err := ctx.State.LoadEntry("missions", "castle_state", "progress")
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if ok && json.Unmarshal(raw, &v) != nil {
|
||||
return out, fmt.Errorf("castle: invalid saved progress")
|
||||
}
|
||||
for _, t := range v.Towers {
|
||||
if out.Towers[t.Mode] == nil {
|
||||
out.Towers[t.Mode] = map[uint64]bool{}
|
||||
}
|
||||
out.Towers[t.Mode][t.ID] = true
|
||||
}
|
||||
seasons := []map[uint64]floor{v.Floors}
|
||||
archived, err := ctx.State.ListEntries("missions", "castle_seasons")
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for key, raw := range archived {
|
||||
floors := map[uint64]floor{}
|
||||
if err := json.Unmarshal(raw, &floors); err != nil {
|
||||
return out, fmt.Errorf("castle: invalid archived season %s", key)
|
||||
}
|
||||
seasons = append(seasons, floors)
|
||||
}
|
||||
for _, floors := range seasons {
|
||||
for id, f := range floors {
|
||||
out.PrideFought[id] = true
|
||||
if f.Highest > 0 {
|
||||
out.PrideCleared[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out.TotalWarBest = sum(v.TotalWarScores)
|
||||
return out, nil
|
||||
}
|
||||
@@ -36,6 +36,7 @@ type Service struct {
|
||||
equipment *assets.EquipmentInventory
|
||||
wallet *assets.Wallet
|
||||
totalWarCompletion func(command.Context, string, uint64, []uint64) error
|
||||
totalWarSettled func(command.Context, uint64) error
|
||||
totalWarTextCheck func(command.Context, string, string) error
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,11 @@ func (s *Service) totalWarEnd(ctx command.Context, v *state, req []byte) ([]byte
|
||||
if len(items) != 0 && len(items) != len(v.TotalWarRun.Costumes) {
|
||||
return nil, fmt.Errorf("castle: missing total war attacker score")
|
||||
}
|
||||
if len(scores) > 0 && s.totalWarSettled != nil {
|
||||
if e = s.totalWarSettled(ctx, total); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
if len(scores) > 0 && (len(v.TotalWarScores) == 0 || total > sum(v.TotalWarScores)) {
|
||||
if s.totalWarCompletion != nil {
|
||||
if e = s.totalWarCompletion(ctx, v.TotalWarRun.Identity, total, v.TotalWarRun.Costumes); e != nil {
|
||||
@@ -207,6 +212,11 @@ func (s *Service) validateSavedTotalWarBattle(ctx command.Context, v *state, blu
|
||||
return nil
|
||||
}
|
||||
|
||||
// AttachTotalWarSettled observes every settled attempt with its total damage.
|
||||
func (s *Service) AttachTotalWarSettled(f func(command.Context, uint64) error) {
|
||||
s.totalWarSettled = f
|
||||
}
|
||||
|
||||
func (s *Service) AttachTotalWarCompletion(f func(command.Context, string, uint64, []uint64) error) {
|
||||
s.totalWarCompletion = f
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
accountstate "bd2server/internal/server/storage/account"
|
||||
"bd2server/internal/server/storage/instanceid"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"context"
|
||||
@@ -139,7 +140,7 @@ func (f *totalWarFixture) command(t *testing.T, run func(command.Context, totalW
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: "total-war-account", SessionID: "login"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: "total-war-account", SessionID: "login"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(f.path), "instance-ids.db"))}
|
||||
rt := f.open(t, ctx)
|
||||
e = run(ctx, rt)
|
||||
if wantError {
|
||||
|
||||
@@ -33,6 +33,19 @@ func (s *Service) AttachDispatchProgress(progress func(command.Context, uint64)
|
||||
s.dispatchProgress = progress
|
||||
}
|
||||
|
||||
// AttachAPSpent observes hunting AP a battle or a dispatch spends directly;
|
||||
// exchanges through the event economy report their own costs.
|
||||
func (s *Service) AttachAPSpent(spent func(command.Context, uint64) error) {
|
||||
s.apSpent = spent
|
||||
}
|
||||
|
||||
func (s *Service) recordAPSpent(ctx command.Context, cost uint64) error {
|
||||
if s.apSpent == nil || cost == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.apSpent(ctx, cost)
|
||||
}
|
||||
|
||||
func dispatchPlayed(j dispatchJob, seconds uint64) uint64 {
|
||||
if seconds == 0 {
|
||||
return j.Count
|
||||
|
||||
@@ -52,6 +52,7 @@ type Service struct {
|
||||
dispatchExchange func(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
|
||||
dispatchBonus func(*gamedata.DispatchDesign, []gamedata.BattleReward) ([]gamedata.BattleReward, error)
|
||||
dispatchProgress func(command.Context, uint64) error
|
||||
apSpent func(command.Context, uint64) error
|
||||
eligibility func(ctx command.Context, _ int, _ uint64) error
|
||||
grant func(command.Context, string, []gamedata.Reward) ([]byte, error)
|
||||
apDesign *gamedata.HuntingAPDesign
|
||||
|
||||
@@ -100,10 +100,13 @@ func (s *Service) exchangeAP(costs, rewards []gamedata.Reward) (snapshot, error)
|
||||
p = &st.Bonus
|
||||
}
|
||||
if cost {
|
||||
if *p < r.Count {
|
||||
// The client spends free AP first and takes the rest from bonus AP,
|
||||
// whichever of the two the cost names.
|
||||
if st.Free+st.Bonus < r.Count {
|
||||
return fmt.Errorf("hunting: insufficient AP")
|
||||
}
|
||||
*p -= r.Count
|
||||
fromFree := min(st.Free, r.Count)
|
||||
st.Free, st.Bonus = st.Free-fromFree, st.Bonus-(r.Count-fromFree)
|
||||
} else {
|
||||
if r.Count > 2147483647-*p {
|
||||
return fmt.Errorf("hunting: AP overflow")
|
||||
|
||||
@@ -221,6 +221,9 @@ func (s *Service) CompleteBattle(ctx command.Context, pack int, mode, monster, d
|
||||
next.Bonus -= cost - next.Free
|
||||
next.Free = 0
|
||||
}
|
||||
if err := s.recordAPSpent(ctx, cost); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
st := next.Packs[strconv.Itoa(pack)]
|
||||
if monster == g.BossID {
|
||||
if st.Highest < g.ID {
|
||||
@@ -547,6 +550,9 @@ func (s *Service) handleDispatch(ctx command.Context, path string, req []byte, s
|
||||
} else {
|
||||
next.Free -= free
|
||||
next.Bonus -= bonus
|
||||
if e = s.recordAPSpent(ctx, free+bonus); e != nil {
|
||||
return code, nil, true, e
|
||||
}
|
||||
}
|
||||
if path == "/HuntDispatchStart" {
|
||||
now := uint64(time.Now().UnixMilli())
|
||||
|
||||
@@ -73,7 +73,7 @@ func assertReservedOffer(t *testing.T, response, expected []byte) {
|
||||
}
|
||||
|
||||
// LocalTextTable 7900025/26/84 and 7900122/23/29 (queried with gamedata_db.py,
|
||||
// 20261012190548) define loss retries, one first-clear reward, run inventory,
|
||||
// 20261021182514) define loss retries, one first-clear reward, run inventory,
|
||||
// post-battle shop refresh, and reservations. Request/response fields and base64
|
||||
// process payload are independently specified by 2.36.7 Proto.Net and IBPacket.
|
||||
func TestBoardLifecyclePreservesBattleReservationAndFirstClear(t *testing.T) {
|
||||
|
||||
@@ -390,6 +390,8 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int,
|
||||
var resultCharacters [][]byte
|
||||
finishedHealth := make(map[uint64]uint64)
|
||||
participants := make(map[uint64]bool)
|
||||
borrowed := make(map[uint64]bool)
|
||||
seenResult := make(map[uint64]bool)
|
||||
if s.commitHealth != nil {
|
||||
for _, character := range state.InitialBlue {
|
||||
Index, _, err := wire.Varint(character, 2)
|
||||
@@ -398,6 +400,7 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int,
|
||||
}
|
||||
if Index != 0 {
|
||||
participants[Index] = true
|
||||
borrowed[Index] = value(character, 38) != 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -408,13 +411,17 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int,
|
||||
if err != nil || !present || !participants[Index] {
|
||||
return errors.New("battle: result character was not a battle participant")
|
||||
}
|
||||
if _, duplicate := finishedHealth[Index]; duplicate {
|
||||
if seenResult[Index] {
|
||||
return errors.New("battle: duplicate result character")
|
||||
}
|
||||
seenResult[Index] = true
|
||||
hp, _, err := wire.Varint(field.Value, 3)
|
||||
if err != nil || hp > math.MaxInt64 {
|
||||
return errors.New("battle: invalid result health")
|
||||
}
|
||||
if borrowed[Index] {
|
||||
return nil
|
||||
}
|
||||
finishedHealth[Index] = hp
|
||||
}
|
||||
resultCharacters = append(resultCharacters, field.Value)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package pvp
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
|
||||
// BestMirrorRankID is the best (lowest) MirrorRankTable ID the account has
|
||||
// reached: every recorded promotion claim plus the current season rank once
|
||||
// the account has fought this season. Zero means no rank was reached.
|
||||
func (s *Service) BestMirrorRankID(ctx command.Context) (uint64, error) {
|
||||
var best uint64
|
||||
reach := func(id uint64) {
|
||||
if id != 0 && (best == 0 || id < best) {
|
||||
best = id
|
||||
}
|
||||
}
|
||||
entries, err := ctx.State.ListEntries("pvp", "promotion_claims")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for key := range entries {
|
||||
_, raw, found := strings.Cut(key, ":")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
reach(id)
|
||||
}
|
||||
season, err := s.current(Mirror)
|
||||
if err != nil {
|
||||
return best, nil
|
||||
}
|
||||
p, err := s.progress(Mirror, season.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if p.Attacks == 0 {
|
||||
return best, nil
|
||||
}
|
||||
entry, err := s.rank(Mirror, season.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rank, err := s.rules.Design.MirrorRank(season.ID, p.VP, entry.Rank)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
reach(rank.ID)
|
||||
return best, nil
|
||||
}
|
||||
@@ -18,11 +18,14 @@ type OwnedSnapshotBuilder struct {
|
||||
Collection *roster.CollectionStore
|
||||
Equipment *assets.EquipmentInventory
|
||||
Buffs func(command.Context) ([]gamedata.PictorialBuffStat, error)
|
||||
OwnerIndex uint64
|
||||
// CostumeCosts returns the current colosseum price of every ranked
|
||||
// costume; unranked costumes cost ColosseumDefaults.CostDefault.
|
||||
CostumeCosts func(command.Context) (map[uint64]uint64, error)
|
||||
OwnerIndex uint64
|
||||
}
|
||||
|
||||
func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (FullSnapshot, error) {
|
||||
if b.Design == nil || b.Characters == nil || b.Collection == nil || b.Equipment == nil || b.Buffs == nil || b.OwnerIndex == 0 {
|
||||
if b.Design == nil || b.Characters == nil || b.Collection == nil || b.Equipment == nil || b.Buffs == nil || b.CostumeCosts == nil || b.OwnerIndex == 0 {
|
||||
return FullSnapshot{}, fmt.Errorf("pvp: incomplete snapshot builder")
|
||||
}
|
||||
previousContents := map[uint64][]byte{}
|
||||
@@ -62,13 +65,23 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful
|
||||
for _, item := range allCostumes {
|
||||
costumeByIndex[item.InvenIndex] = item
|
||||
}
|
||||
var banned []uint64
|
||||
var banned, costLimit []uint64
|
||||
var costs map[uint64]uint64
|
||||
if r.Mode == Colosseum {
|
||||
banned, e = b.Design.ColosseumRule(r.Season, 30)
|
||||
if e != nil {
|
||||
return FullSnapshot{}, e
|
||||
}
|
||||
if costLimit, e = b.Design.ColosseumRule(r.Season, 32); e != nil {
|
||||
return FullSnapshot{}, e
|
||||
}
|
||||
if len(costLimit) != 0 {
|
||||
if costs, e = b.CostumeCosts(ctx); e != nil {
|
||||
return FullSnapshot{}, e
|
||||
}
|
||||
}
|
||||
}
|
||||
var totalCost uint64
|
||||
var result FullSnapshot
|
||||
var bindings []assets.PresetEquipmentBinding
|
||||
usedEquipment := map[uint64]bool{}
|
||||
@@ -95,6 +108,11 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful
|
||||
if slices.Contains(banned, costume.ID) {
|
||||
return result, fmt.Errorf("pvp: selected costume banned this season")
|
||||
}
|
||||
if cost, ranked := costs[costume.ID]; ranked {
|
||||
totalCost += cost
|
||||
} else {
|
||||
totalCost += b.Design.Colosseum.CostDefault
|
||||
}
|
||||
if e = b.validateSkills(index, entry, costumeByIndex); e != nil {
|
||||
return result, e
|
||||
}
|
||||
@@ -188,6 +206,9 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(costLimit) != 0 && totalCost > costLimit[0] {
|
||||
return result, fmt.Errorf("pvp: costume cost %d exceeds season limit %d", totalCost, costLimit[0])
|
||||
}
|
||||
for index := range requested {
|
||||
if !deckCharacters[index] {
|
||||
return result, fmt.Errorf("pvp: saved equipment references a character outside formation")
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package pvp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
)
|
||||
|
||||
// GameData 20261021182514: ColosseumSeasonTable gives season 47 rule group 25
|
||||
// and season 46 group 24; only groups 25/26 carry rule 32
|
||||
// (C_RULE_COSTUME_COST_LIMIT) with value 160. Unranked costumes cost 30.
|
||||
func TestColosseumFormationRejectsCostumeCostAboveSeasonLimit(t *testing.T) {
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: "a"}, State: stateio.NewMemory()}
|
||||
var characters []roster.Character
|
||||
var costumes []roster.Costume
|
||||
for i := uint64(1); i <= 4; i++ {
|
||||
characters = append(characters, roster.Character{InvenIndex: i, ID: 100 + i, Level: 1})
|
||||
costumes = append(costumes, roster.Costume{InvenIndex: 10 + i, ID: 1000 + i, UseChar: i})
|
||||
}
|
||||
inventory, err := assets.OpenInventory(ctx, stateio.RootStore{}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
characterStore, err := roster.OpenCharacterStore(ctx, stateio.RootStore{}, characters, inventory, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, costumes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
equipment, err := assets.OpenEquipmentInventory(ctx, stateio.RootStore{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = characterStore.AttachCollection(ctx, collection); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = collection.BindBaseCharacters(ctx, characters); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = equipment.AttachCharacters(ctx, characterStore); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = equipment.AttachSlots(ctx, map[uint64]uint64{700: 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
builder := &OwnedSnapshotBuilder{
|
||||
Design: &gamedata.PvpDesign{
|
||||
Colosseum: gamedata.ColosseumDefaults{CostDefault: 30},
|
||||
ColosseumSeasons: map[uint64]uint64{46: 24, 47: 25},
|
||||
ColosseumRules: map[uint64]map[uint64][]uint64{24: {}, 25: {32: {160}}},
|
||||
},
|
||||
Characters: characterStore, Collection: collection, Equipment: equipment, OwnerIndex: 1,
|
||||
Buffs: func(command.Context) ([]gamedata.PictorialBuffStat, error) { return nil, nil },
|
||||
CostumeCosts: func(command.Context) (map[uint64]uint64, error) {
|
||||
return map[uint64]uint64{1001: 50, 1002: 50, 1003: 50}, nil
|
||||
},
|
||||
}
|
||||
deck := func(indices ...uint64) [][]byte {
|
||||
var out [][]byte
|
||||
for _, index := range indices {
|
||||
out = append(out, wire.AppendVarint(wire.AppendVarint(nil, 1, index), 4, 10+index))
|
||||
}
|
||||
return out
|
||||
}
|
||||
if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 47, Deck: deck(1, 2, 4)}); err != nil {
|
||||
t.Fatalf("cost 130 within limit 160 rejected: %v", err)
|
||||
}
|
||||
if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 47, Deck: deck(1, 2, 3, 4)}); err == nil || !strings.Contains(err.Error(), "exceeds season limit") {
|
||||
t.Fatalf("cost 180 above limit 160 accepted: %v", err)
|
||||
}
|
||||
if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 46, Deck: deck(1, 2, 3, 4)}); err != nil {
|
||||
t.Fatalf("season without cost rule enforced a limit: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package battle
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func questVictoryKey(pack int, quest, difficulty uint64) string {
|
||||
return fmt.Sprintf("%d:%d:%d", pack, difficulty, quest)
|
||||
}
|
||||
|
||||
func (s *Service) HasWonQuest(ctx command.Context, pack, quest, difficulty int) (bool, error) {
|
||||
if ctx.State == nil || pack <= 0 || quest <= 0 || difficulty < 0 || difficulty > 2 {
|
||||
return false, nil
|
||||
}
|
||||
receipt, found, err := ctx.State.LoadEntry("battle", "quest_victory", questVictoryKey(pack, uint64(quest), uint64(difficulty)))
|
||||
return found && len(receipt) != 0, err
|
||||
}
|
||||
|
||||
func (s *Service) recordQuestVictory(ctx command.Context, state *battleState) error {
|
||||
if ctx.State == nil || state.Mode != 1 || state.Quest == 0 || state.Pack <= 0 {
|
||||
return nil
|
||||
}
|
||||
if s.currentDifficulty == nil {
|
||||
return fmt.Errorf("battle: quest victory difficulty unavailable")
|
||||
}
|
||||
difficulty, err := s.currentDifficulty(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loader := s.loadDifficultyDeck
|
||||
if loader == nil {
|
||||
loader = gamedata.ResolveQuestBattleDeck
|
||||
}
|
||||
enteredDeck := value(state.EntryResponse, 2)
|
||||
if enteredDeck == 0 {
|
||||
return fmt.Errorf("battle: quest victory entry deck unavailable")
|
||||
}
|
||||
resolved, err := loader(s.gameDataRoot, s.gameDataVersion, state.Pack, state.Monster, enteredDeck, difficulty)
|
||||
if err != nil {
|
||||
return fmt.Errorf("battle: verify quest victory difficulty: %w", err)
|
||||
}
|
||||
if resolved.DeckID != enteredDeck || !slices.Contains(resolved.QuestIDs, state.Quest) || state.EnterReceipt == "" {
|
||||
return fmt.Errorf("battle: quest victory differs from entered encounter")
|
||||
}
|
||||
return ctx.State.PutEntry("battle", "quest_victory", questVictoryKey(state.Pack, state.Quest, difficulty), []byte(state.EnterReceipt))
|
||||
}
|
||||
@@ -271,6 +271,11 @@ func (s *Service) CompleteBattle(ctx command.Context, b []byte, key string) ([]b
|
||||
out = wire.AppendVarint(out, 23, f)
|
||||
out = wire.AppendBytes(out, 24, roomWire(*cleared))
|
||||
}
|
||||
if s.options.OnBattle != nil {
|
||||
if e = s.options.OnBattle(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
if e = s.save(ctx, v); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
@@ -81,9 +81,10 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) {
|
||||
period := Period{Season: 1, Regular: 1, Active: true}
|
||||
economy := &testEconomy{}
|
||||
tickets := uint64(0)
|
||||
battles := 0
|
||||
proof := battle.SettlementEvidence{}
|
||||
open := func() *Service {
|
||||
s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Access: func(command.Context) error { return nil }, Economy: economy, Owner: 1, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, count uint64) error { tickets += count; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }})
|
||||
s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Access: func(command.Context) error { return nil }, Economy: economy, Owner: 1, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, count uint64) error { tickets += count; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }, OnBattle: func(command.Context) error { battles++; return nil }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
@@ -197,9 +198,13 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) {
|
||||
proof = battle.SettlementEvidence{Receipt: identity, Mode: mode, Deck: deck, Round: 0}
|
||||
end := req(seq, 1)
|
||||
seq++
|
||||
beforeBattles := battles
|
||||
if _, e = s.CompleteBattle(ctx, end, identity); e == nil {
|
||||
t.Fatal("settled a room without any started battle")
|
||||
}
|
||||
if battles != beforeBattles {
|
||||
t.Fatal("rejected settlement counted a battle")
|
||||
}
|
||||
var blue [][]byte
|
||||
for i, c := range r.Characters {
|
||||
var costume costume
|
||||
@@ -226,9 +231,15 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) {
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if battles != beforeBattles+1 {
|
||||
t.Fatalf("settled battle reported %d times", battles-beforeBattles)
|
||||
}
|
||||
if _, e = s.CompleteBattle(ctx, end, identity); e == nil {
|
||||
t.Fatal("domain paid a settled room twice")
|
||||
}
|
||||
if battles != beforeBattles+1 {
|
||||
t.Fatal("settled room reported a battle twice")
|
||||
}
|
||||
if len(out) == 0 {
|
||||
t.Fatal("battle omitted client state")
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ type Options struct {
|
||||
Evidence func(command.Context) battle.SettlementEvidence
|
||||
Ranking Ranking
|
||||
Publish func(command.Context, uint64, uint64, uint64, uint64) error
|
||||
OnBattle func(command.Context) error
|
||||
Owner uint64
|
||||
}
|
||||
type Service struct {
|
||||
|
||||
@@ -242,6 +242,11 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (resu
|
||||
return code, nil, true, err
|
||||
}
|
||||
}
|
||||
if path == "/BattleEnd" && value(request, 2) == 1 {
|
||||
if err = s.recordQuestVictory(ctx, &before); err != nil {
|
||||
return code, nil, true, err
|
||||
}
|
||||
}
|
||||
if s.completion != nil {
|
||||
completion := before.completion(value(request, 2) == 1)
|
||||
var extra []byte
|
||||
@@ -353,6 +358,8 @@ func (s *Service) resume(ctx command.Context) (int, []byte, bool, error) {
|
||||
out = wire.AppendVarint(out, 13, value(user, 4))
|
||||
out = wire.AppendVarint(out, 14, value(user, 4))
|
||||
out = wire.AppendVarint(out, 17, value(user, 1))
|
||||
// The client opens the armor-break gate at battle start; proto3 would otherwise read false.
|
||||
out = wire.AppendVarint(out, 36, 1)
|
||||
}
|
||||
if (state.Mode == 23 || state.Mode == 26) && s.externalResume != nil {
|
||||
extra, err := s.externalResume(ctx, state.Mode, state.EnterReceipt)
|
||||
@@ -397,7 +404,7 @@ func (s *Service) previous(ctx command.Context, request []byte) (int, []byte, bo
|
||||
}
|
||||
snapshot := state.previousSnapshot()
|
||||
var out []byte
|
||||
for from, to := range map[int]int{8: 1, 9: 2, 10: 3, 12: 4, 15: 5, 16: 6, 28: 9, 29: 10, 30: 11, 31: 12, 32: 13} {
|
||||
for from, to := range map[int]int{8: 1, 9: 2, 10: 3, 12: 4, 15: 5, 16: 6, 28: 9, 29: 10, 30: 11, 31: 12, 32: 13, 35: 15, 36: 16} {
|
||||
if err := wire.Walk(snapshot, func(f wire.Field) error {
|
||||
if f.Number != from {
|
||||
return nil
|
||||
|
||||
@@ -42,6 +42,8 @@ func startPacket(seq, turn, hp, sp uint64, blue bool) ([]byte, []byte) {
|
||||
checkpoint = wire.AppendVarint(checkpoint, 10, 13)
|
||||
checkpoint = wire.AppendVarint(checkpoint, 28, turn+20)
|
||||
checkpoint = wire.AppendBytes(checkpoint, 29, wire.AppendVarint(nil, 1, turn+700))
|
||||
checkpoint = wire.AppendVarint(checkpoint, 35, turn+30)
|
||||
checkpoint = wire.AppendVarint(checkpoint, 36, boolNumber(turn == 1))
|
||||
checkpoint = wire.AppendVarint(checkpoint, 101, boolNumber(blue))
|
||||
req := wire.AppendVarint(packet(seq), 2, 80)
|
||||
deck := wire.AppendVarint(nil, 1, 9001)
|
||||
@@ -85,7 +87,7 @@ func TestCheckpointReopenResumesAndRetriesPreviousBlueTurn(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(one(body, 1)) != base64.StdEncoding.EncodeToString(first) || value(body, 2) != 5 || value(body, 9) != 21 || value(one(body, 10), 1) != 701 || value(body, 7) != 0 {
|
||||
if string(one(body, 1)) != base64.StdEncoding.EncodeToString(first) || value(body, 2) != 5 || value(body, 9) != 21 || value(one(body, 10), 1) != 701 || value(body, 7) != 0 || value(body, 15) != 31 || value(body, 16) != 1 {
|
||||
t.Fatalf("retry did not restore previous BLUE boundary: %x", body)
|
||||
}
|
||||
play(t, s, ctx, 3, 1, 100, 5, true)
|
||||
|
||||
@@ -49,6 +49,8 @@ type Service struct {
|
||||
resetSeconds int64
|
||||
owned func() []uint64
|
||||
hasEpisode func(uint64) bool
|
||||
datingTicket uint64
|
||||
holdsTicket func(command.Context, uint64) bool
|
||||
}
|
||||
|
||||
func Open(ctx command.Context, store stateio.Store, d *gamedata.CafeteriaDesign, e Economy) (*Service, error) {
|
||||
@@ -94,7 +96,14 @@ func Open(ctx command.Context, store stateio.Store, d *gamedata.CafeteriaDesign,
|
||||
}
|
||||
func (s *Service) AttachOwnedCostumes(f func() []uint64) { s.owned = f }
|
||||
func (s *Service) AttachDatingHasEpisode(f func(uint64) bool) { s.hasEpisode = f }
|
||||
func (s *Service) SetResetSeconds(v int64) { s.resetSeconds = v }
|
||||
|
||||
// AttachDatingTicket names the content ticket the client checks before
|
||||
// claiming the introduction (ContentUnlockDating) and how to test ownership.
|
||||
func (s *Service) AttachDatingTicket(ticket uint64, holds func(command.Context, uint64) bool) {
|
||||
s.datingTicket, s.holdsTicket = ticket, holds
|
||||
}
|
||||
|
||||
func (s *Service) SetResetSeconds(v int64) { s.resetSeconds = v }
|
||||
func (s *Service) day() string {
|
||||
return s.now().UTC().Add(time.Duration(9*3600-s.resetSeconds) * time.Second).Format("2006-01-02")
|
||||
}
|
||||
@@ -181,6 +190,9 @@ func noteWire(n *note) []byte {
|
||||
}
|
||||
func val(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v }
|
||||
|
||||
// contentTicketType is EElementType.ContentTicket.
|
||||
const contentTicketType = 19
|
||||
|
||||
var codes = map[string]int{"/CafeteriaInfo": 351, "/CafeteriaSpawnReset": 352, "/CafeteriaLevelUp": 353, "/CafeteriaManageItemAdd": 354, "/CafeteriaRegularCostumeInteractionReward": 355, "/CafeteriaRegularCostumeInteractionAllReward": 356, "/CafeteriaCumulativeReward": 357, "/CafeteriaRegularCostumeNoteInfo": 358, "/CafeteriaRegularCostumeNoteReward": 359, "/CafeteriaRegularCostumeNoteAllReward": 360, "/CafeteriaIntroductionStoryReward": 371, "/CafeteriaDailyConnectionCostumeRefresh": 376, "/CafeteriaRareNpcInteractionReward": 413, "/CafeteriaEventNpcInteractionReward": 414}
|
||||
|
||||
func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) {
|
||||
@@ -266,14 +278,16 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
|
||||
return out, nil
|
||||
case "/CafeteriaIntroductionStoryReward":
|
||||
if s.state.Introduction {
|
||||
return nil, nil
|
||||
bundle, e := s.restoreDatingTicket(ctx)
|
||||
if e != nil || bundle == nil {
|
||||
return nil, e
|
||||
}
|
||||
return wire.AppendBytes(nil, 1, bundle), nil
|
||||
}
|
||||
d := s.design.Default
|
||||
bundle, e := s.economy.Apply(ctx, identity, nil, []gamedata.Reward{{Type: d.V(31), ID: d.V(30), Count: d.V(29)}})
|
||||
bundle, e := s.grantIntroduction(ctx, identity)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
s.state.Introduction = true
|
||||
return wire.AppendBytes(nil, 1, bundle), nil
|
||||
case "/CafeteriaManageItemAdd":
|
||||
id := s.state.Manage + 1
|
||||
@@ -505,3 +519,37 @@ func sortedNotes(m map[uint64]*note) []uint64 {
|
||||
slices.Sort(ids)
|
||||
return ids
|
||||
}
|
||||
|
||||
// restoreDatingTicket grants the dating unlock ticket to a player whose
|
||||
// introduction is complete but who does not hold it. The client claims the
|
||||
// introduction on every cafeteria entry until the ticket exists, so ownership,
|
||||
// not the introduction flag, decides; the fixed identity grants it once.
|
||||
func (s *Service) restoreDatingTicket(ctx command.Context) ([]byte, error) {
|
||||
if s.datingTicket == 0 || s.holdsTicket == nil || s.holdsTicket(ctx, s.datingTicket) {
|
||||
return nil, nil
|
||||
}
|
||||
return s.economy.Apply(ctx, fmt.Sprintf("cafeteria:introduction-ticket:%d", s.datingTicket), nil, []gamedata.Reward{{Type: contentTicketType, ID: s.datingTicket, Count: 1}})
|
||||
}
|
||||
|
||||
// grantIntroduction pays the CafeteriaDefaultTable visual-novel end reward and
|
||||
// records the introduction as finished.
|
||||
func (s *Service) grantIntroduction(ctx command.Context, identity string) ([]byte, error) {
|
||||
d := s.design.Default
|
||||
bundle, err := s.economy.Apply(ctx, identity, nil, []gamedata.Reward{{Type: d.V(31), ID: d.V(30), Count: d.V(29)}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.state.Introduction = true
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
// ReconcileIntroduction runs at login: a finished introduction regains a
|
||||
// missing dating ticket. Unfinished ones wait for the client's claim on the
|
||||
// first entry into the cafeteria game card.
|
||||
func (s *Service) ReconcileIntroduction(ctx command.Context) error {
|
||||
if !s.state.Introduction {
|
||||
return nil
|
||||
}
|
||||
_, err := s.restoreDatingTicket(ctx)
|
||||
return err
|
||||
}
|
||||
@@ -221,3 +221,45 @@ func TestCafeteriaInteractionCapIsSharedAndResets(t *testing.T) {
|
||||
t.Fatal("missed days generated retroactive rewards")
|
||||
}
|
||||
}
|
||||
|
||||
// Login never pays an unfinished introduction: it belongs to the first entry
|
||||
// into the cafeteria game card. A finished one only regains a spent ticket.
|
||||
func TestCafeteriaLoginOnlyRestoresTheTicketOfAFinishedIntroduction(t *testing.T) {
|
||||
d := liveDesign(t)
|
||||
store := stateio.NewMemory()
|
||||
ctx := command.Context{Identity: command.Identity{SessionID: "introduction"}, State: store}
|
||||
money := &ledger{balances: map[[2]uint64]uint64{}}
|
||||
intro := [2]uint64{d.Default.V(31), d.Default.V(30)}
|
||||
const ticket = 3007 // ContentOpenTable group19/detail1 (dating) ticket in current GameData
|
||||
held := false
|
||||
open := func() *Service {
|
||||
t.Helper()
|
||||
s, e := Open(ctx, stateio.RootStore{}, d, money)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.AttachDatingTicket(ticket, func(command.Context, uint64) bool { return held })
|
||||
s.AttachOwnedCostumes(func() []uint64 { return []uint64{d.Costumes.Groups[0][0]} })
|
||||
s.AttachDatingHasEpisode(func(uint64) bool { return true })
|
||||
return s
|
||||
}
|
||||
if e := open().ReconcileIntroduction(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if money.balances[intro] != 0 || money.balances[[2]uint64{19, ticket}] != 0 {
|
||||
t.Fatalf("login paid an unfinished introduction: introduction %d ticket %d", money.balances[intro], money.balances[[2]uint64{19, ticket}])
|
||||
}
|
||||
if _, _, _, e := open().Handle(ctx, "/CafeteriaIntroductionStoryReward", wire.AppendVarint(nil, 1, 1)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if money.balances[intro] != d.Default.V(29) {
|
||||
t.Fatalf("introduction reward %d, want %d", money.balances[intro], d.Default.V(29))
|
||||
}
|
||||
// The ledger does not expand the box, so the ticket counts as spent.
|
||||
if e := open().ReconcileIntroduction(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if money.balances[intro] != d.Default.V(29) || money.balances[[2]uint64{19, ticket}] != 1 {
|
||||
t.Fatalf("finished introduction login: introduction %d ticket %d, want %d and 1", money.balances[intro], money.balances[[2]uint64{19, ticket}], d.Default.V(29))
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ type Service struct {
|
||||
equipmentCatalog *gamedata.EquipmentGachaCatalog
|
||||
equipmentInventory *assets.EquipmentInventory
|
||||
onPreview func(ctx command.Context) error
|
||||
onDraw func(ctx command.Context, _ uint64) error
|
||||
onDraw func(ctx command.Context, groupID, count uint64) error
|
||||
schedule *ScheduleSeed
|
||||
previewEventIndex uint64
|
||||
|
||||
@@ -42,7 +42,7 @@ func (s *Service) TransientVersion() uint64 {
|
||||
return s.transientVersion
|
||||
}
|
||||
|
||||
func (s *Service) AttachDrawMission(callback func(ctx command.Context, _ uint64) error) {
|
||||
func (s *Service) AttachDrawMission(callback func(ctx command.Context, groupID, count uint64) error) {
|
||||
s.onDraw = callback
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ func NewService(design *gamedata.InfiniteGachaDesign, regular *gamedata.RegularG
|
||||
return &Service{design: design, regular: regular, collection: collection, wallet: wallet, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func (s *Service) dailyFreeAllowance(groupID, base uint64) (uint64, bool, error) {
|
||||
func (s *Service) dailyAllowance(groupID, base uint64, paid bool) (uint64, bool, error) {
|
||||
if s.schedule == nil {
|
||||
return 0, false, nil
|
||||
}
|
||||
@@ -105,10 +105,15 @@ func (s *Service) dailyFreeAllowance(groupID, base uint64) (uint64, bool, error)
|
||||
if entry.GroupID != groupID || now < 0 || uint64(now) < entry.StartTime || uint64(now) > entry.EndTime {
|
||||
continue
|
||||
}
|
||||
if entry.FreeCountBonus {
|
||||
bonus := s.regular.GachaEventAddFreeCount()
|
||||
bonus := uint64(0)
|
||||
if paid && entry.CashCountBonus {
|
||||
bonus = s.regular.GachaEventAddDailyPayCount()
|
||||
} else if !paid && entry.FreeCountBonus {
|
||||
bonus = s.regular.GachaEventAddFreeCount()
|
||||
}
|
||||
if bonus != 0 {
|
||||
if ^uint64(0)-base < bonus {
|
||||
return 0, false, errors.New("gacha: daily free allowance overflows")
|
||||
return 0, false, errors.New("gacha: daily allowance overflows")
|
||||
}
|
||||
base += bonus
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
accountstate "bd2server/internal/server/storage/account"
|
||||
"bd2server/internal/server/storage/instanceid"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
)
|
||||
|
||||
@@ -68,7 +69,7 @@ func (a *historyAccount) call(t *testing.T, path string, raw []byte) ([]byte, er
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: a.name, SessionID: "draw-session"}, State: tx}
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: a.name, SessionID: "draw-session"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(a.path), "instance-ids.db"))}
|
||||
collection, e := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
|
||||
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user