feat(client): register plugins dynamically and add BetterExperience with audio and inventory fixes

This commit is contained in:
Flechazo committed 2026-11-12 17:40:19 +08:00
1 parent 7da29e7bee
commit bae82a859b
52 files changed
+1102 -291

No files matched your search

+3 -1
View File
@@ -56,6 +56,8 @@
- `plugins/CaptureEnvironment/`:独立原版对照客户端的抓包插件,不要装进本地服务端客户端。
- `plugins/GameNames`/`plugins/GameSdk`: 插件开发工具链,让开发过程中使用反混淆名改善开发体验,只有 `GameNames` 需要随同安装。
所有随启动器发布的插件都登记在 `plugins/registry.json`:项目路径、目标框架、输出 DLL、版本键和依赖。新增插件只需在这里加一项,并在 `versions.json` 的 `plugins` 里写上它的版本;只有要求旧插件必须升级时,才在 `minimum_plugins` 里写最低版本。`tools` 里的项目(如 `CaptureEnvironment`)只参与 `check-csharp`,不打包也不下发。
## 可视化客户端工具
BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系统 WebView2 Runtime,macOS 使用系统 WKWebView。它提供以下操作:
@@ -63,7 +65,7 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
- 选择并验证 Brown Dust II 安装目录。
- 填写服务器 origin 和端口,自动写入游戏目录下的 `BepInEx/config/bd2.client.json`。
- 应用带原文件备份的客户端入口补丁。
- 检查 BepInEx 后安装或更新 `BD2LocalIdentity.dll`、`BD2LoginUI.dll`、`BD2CashShop.dll` 及其共享运行时 `BD2.GameNames.dll`。
- 检查 BepInEx 后安装或更新 `plugins/registry.json` 登记的插件及其共享运行时 `BD2.GameNames.dll`。
- 选择官方 CDN、服务器资源源或本地已下载资源。
服主同步官方资源、自建静态 CDN 或配置缓存反代的步骤见 [资源与 CDN 配置指南](RESOURCES.md)。
+11 -17
View File
@@ -3,7 +3,6 @@ package main
import (
"context"
"fmt"
"path/filepath"
"slices"
"bd2server/internal/client/plugin"
@@ -11,7 +10,16 @@ import (
)
func (t task) checkCSharp(projects []string) error {
allowed := csharpProjects()
registry, err := plugin.Load(t.root)
if err != nil {
return err
}
files := map[string]string{}
var allowed []string
for _, project := range registry.Projects(t.root) {
files[project.Name] = project.File
allowed = append(allowed, project.Name)
}
if len(projects) == 0 {
projects = allowed
}
@@ -26,13 +34,7 @@ func (t task) checkCSharp(projects []string) error {
continue
}
seen[project] = true
file := filepath.Join(t.root, "plugins", project, project+".csproj")
for _, definition := range plugin.Definitions() {
if definition.Name() == project {
file = definition.ProjectFile(t.root)
break
}
}
file := files[project]
build, format := "csharp:build:"+project, "csharp:style:"+project
tasks = append(tasks,
taskgraph.Task{Name: build, Run: func(context.Context) error {
@@ -48,11 +50,3 @@ func (t task) checkCSharp(projects []string) error {
tasks = append(tasks, taskgraph.Task{Name: "check-csharp", DependsOn: targets})
return t.execute("check-csharp", tasks...)
}
func csharpProjects() []string {
projects := []string{"GameSdk", "CaptureEnvironment"}
for _, d := range plugin.Definitions() {
projects = append(projects, d.Name())
}
return projects
}
+5 -1
View File
@@ -81,7 +81,11 @@ func (t task) runClient2(args []string) error {
if err := clientplugin.BuildDevelopment(ctx, t.root, game, os.Stdout); err != nil {
return err
}
_, err := clientsetup.InstallPlugins(instance.GameDirectory, clientplugin.Development(t.root))
plugins, err := clientplugin.Development(t.root)
if err != nil {
return err
}
_, err = clientsetup.InstallPlugins(instance.GameDirectory, plugins)
return err
}},
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
+15 -3
View File
@@ -152,7 +152,11 @@ func (r *release) stageAssets() error {
return err
}
}
for _, artifact := range clientplugin.Development(root) {
plugins, err := clientplugin.Development(root)
if err != nil {
return err
}
for _, artifact := range plugins {
if err := copyFile(artifact.Source, filepath.Join(r.client, "plugins", artifact.Name)); err != nil {
return err
}
@@ -223,15 +227,23 @@ func (r *release) writePluginStore() error {
if err != nil {
return err
}
plugins, err := clientplugin.Development(r.task.root)
if err != nil {
return err
}
byID := versions.Plugins.ByID()
store := clientplugin.Store{Version: versions.ClientVersion}
for _, artifact := range clientplugin.Development(r.task.root) {
for _, artifact := range plugins {
version, found := byID[artifact.VersionKey]
if artifact.VersionKey != "" && !found {
return fmt.Errorf("versions.json has no plugins.%s for %s", artifact.VersionKey, artifact.Name)
}
sum, err := util.SHA256File(filepath.Join(r.client, "plugins", artifact.Name))
if err != nil {
return err
}
id := artifact.ID
store.Files = append(store.Files, clientplugin.StoredFile{ID: id, Name: artifact.Name, Version: byID[artifact.VersionKey], SHA256: sum})
store.Files = append(store.Files, clientplugin.StoredFile{ID: id, Name: artifact.Name, Version: version, SHA256: sum})
}
raw, err := json.MarshalIndent(store, "", " ")
if err != nil {
-1
View File
@@ -309,7 +309,6 @@ func (t task) releasePublish(args []string) error {
server := &releasepkg.Component{Version: versions.ServerVersion, Date: date(serverEntry), Notes: serverEntry.Notes(), Image: opts.image,
Migration: &releasepkg.Migration{Kind: serverEntry.Migration, Backup: serverEntry.Backup}, MinimumPlugins: versions.MinimumPlugins.ByID()}
delete(server.MinimumPlugins, "capture_environment")
if serverEntry.Migration != releasepkg.MigrationNone {
server.Migration.Note = i18n.Text{}
for locale, notes := range serverEntry.Notes() {
+5 -1
View File
@@ -127,10 +127,14 @@ func runClientDevelopmentCommand(args []string) (bool, error) {
return buildDevelopmentPlugins(ctx, root, gameDir)
}},
taskgraph.Task{Name: "client:options", DependsOn: []string{"client:plugins"}, Run: func(context.Context) error {
plugins, err := clientplugin.Development(root)
if err != nil {
return err
}
options = clientRunOptions{
versionConfigPath: filepath.Join(root, "versions.json"),
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
plugins: clientplugin.Development(root),
plugins: plugins,
}
return nil
}},
+7 -15
View File
@@ -23,14 +23,8 @@ type Config struct {
MinimumPlugins pluginVersions `json:"minimum_plugins"`
}
type pluginVersions struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
// pluginVersions maps plugin version keys to versions.
type pluginVersions map[string]string
func readConfig(path string, config *Config) error {
raw, err := os.ReadFile(path)
@@ -54,7 +48,7 @@ func GameVersion(path string) (string, error) {
if err := readConfig(path, &config); err != nil {
return "", err
}
if _, err := config.validate("local_identity"); err != nil {
if _, err := config.validate(""); err != nil {
return "", err
}
return config.GameVersion, nil
@@ -106,13 +100,11 @@ namespace Bd2Build
}
func (c Config) validate(plugin string) (string, error) {
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
if c.Plugins.FBattle != "" {
plugins["fbattle"] = c.Plugins.FBattle
}
// An empty plugin validates the file without selecting a version.
plugins := c.Plugins
selected, found := plugins[plugin]
if !found {
return "", fmt.Errorf("unsupported plugin %q", plugin)
if plugin != "" && !found {
return "", fmt.Errorf("versions.json has no plugins.%s", plugin)
}
semver := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
resource := regexp.MustCompile(`^[0-9]{14}$`)
+10 -1
View File
@@ -216,7 +216,16 @@ func (s *Studio) Browse(input Request) (Response, error) {
if dir == "" {
return success("Selection cancelled", nil), nil
}
return success("Installation directory selected", clientsetup.GameStatus{GameDirectory: dir}), nil
// An empty directory is a valid install target, so a failed check
// only reports what is missing instead of rejecting the selection.
status, inspectErr := clientsetup.Inspect(dir, s.versions(dir))
if status.GameDirectory == "" {
status.GameDirectory = dir
}
if inspectErr != nil {
s.log().Info("selected directory is not a ready game client", "directory", dir, "reason", inspectErr)
}
return success("Installation directory selected", status), nil
})
}
+13 -11
View File
@@ -23,9 +23,6 @@ import (
// BuildDevelopment compiles the client plugins as one dependency graph, sharing
// the game SDK and version preparation across the entry projects.
func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Writer) error {
if err := validateDefinitions(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
@@ -38,6 +35,11 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
if err != nil {
return err
}
registry, err := Load(root)
if err != nil {
return err
}
definitions := registry.Plugins
managed := filepath.Join(installation.Data, "Managed")
identity := sha256.Sum256([]byte(root + "\x00" + managed + "\x00" + installation.BepInEx))
work := filepath.Join(root, ".build", "client-plugins", hex.EncodeToString(identity[:12]))
@@ -54,7 +56,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
defer func() { _ = digests.save(digestPath) }()
_, _ = fmt.Fprintln(progress, "Client plugins: checking source, game DLL and output fingerprints...")
cacheStarted := time.Now()
inputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
inputs, err := snapshotInputs(root, managed, installation.BepInEx, registry, digests)
if err != nil {
return err
}
@@ -75,8 +77,8 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
compileInputsDir := filepath.Join(work, "compile-inputs")
sdkInputs := filepath.Join(compileInputsDir, "sdk.g.cs")
namesInputs := filepath.Join(compileInputsDir, "names.g.cs")
sdkFingerprint := dependencyFingerprint(root, inputs, "GameSdk")
namesFingerprint := dependencyFingerprint(root, inputs, "GameNames")
sdkFingerprint := dependencyFingerprint(root, definitions, inputs, "GameSdk")
namesFingerprint := dependencyFingerprint(root, definitions, inputs, "GameNames")
sdkInputsKey := map[string]string{"sdk": sdkFingerprint, "game_version": gameVersion}
for file, sum := range inputs {
if strings.HasPrefix(file, managed+string(filepath.Separator)) || strings.HasPrefix(file, installation.BepInEx+string(filepath.Separator)) {
@@ -140,7 +142,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.VersionKey+".g.cs"), project.VersionKey); err != nil {
return err
}
inputStamp, err := projectFingerprint(root, inputs, project.Name(), filepath.Join(versionDir, project.VersionKey+".g.cs"))
inputStamp, err := projectFingerprint(root, definitions, inputs, project.Name(), filepath.Join(versionDir, project.VersionKey+".g.cs"))
if err != nil {
return err
}
@@ -154,7 +156,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}},
taskgraph.Task{Name: "pluginsCompile", DependsOn: []string{"versionSources"}, Run: func(context.Context) error {
compileStarted := time.Now()
if err := writeAggregateProject(filepath.Join(work, "ClientPlugins.proj"), root); err != nil {
if err := writeAggregateProject(filepath.Join(work, "ClientPlugins.proj"), root, definitions); err != nil {
return err
}
_, _ = fmt.Fprintf(progress, "Client plugins: compiling all %d plugins as one parallel dependency graph...\n", len(definitions))
@@ -190,7 +192,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
outputs = append(outputs, filepath.Join(versionDir, project.VersionKey+".g.cs"), filepath.Join(compileInputsDir, project.VersionKey+".g.cs"))
}
}
if err := verifyDependencyOutputs(root); err != nil {
if err := verifyDependencyOutputs(root, definitions); err != nil {
return err
}
sums := make(map[string]string, len(outputs))
@@ -201,7 +203,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}
sums[output] = sum
}
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, registry, digests)
if err != nil {
return err
}
@@ -289,7 +291,7 @@ func runPluginBuild(ctx context.Context, root string, progress io.Writer, args .
return nil
}
func writeAggregateProject(path, root string) error {
func writeAggregateProject(path, root string, definitions []Definition) error {
var content, properties bytes.Buffer
content.WriteString("<Project DefaultTargets=\"Build\"><ItemGroup>")
properties.WriteString("<Project>")
+14 -10
View File
@@ -68,8 +68,8 @@ func (cache fileDigestCache) save(path string) error {
return saveBuildJSON(path, data)
}
func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[string]string, error) {
files, err := developmentInputs(root, managed, bep)
func snapshotInputs(root, managed, bep string, registry Registry, cache fileDigestCache) (map[string]string, error) {
files, err := developmentInputs(root, managed, bep, registry)
if err != nil {
return nil, err
}
@@ -84,7 +84,7 @@ func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[strin
return inputs, nil
}
func projectFingerprint(root string, inputs map[string]string, project, versionSource string) (string, error) {
func projectFingerprint(root string, definitions []Definition, inputs map[string]string, project, versionSource string) (string, error) {
var definition Definition
for _, candidate := range definitions {
if candidate.Name() == project {
@@ -92,7 +92,7 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
break
}
}
relevant := selectDependencyInputs(root, inputs, definition)
relevant := selectDependencyInputs(root, definitions, inputs, definition)
if versionSource != "" {
sum, err := util.SHA256File(versionSource)
if err != nil {
@@ -103,8 +103,8 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
return digestInputs(relevant), nil
}
func selectDependencyInputs(root string, inputs map[string]string, definition Definition) map[string]string {
projects := definition.dependencyProjects()
func selectDependencyInputs(root string, definitions []Definition, inputs map[string]string, definition Definition) map[string]string {
projects := definition.dependencyProjects(definitions)
relevant := make(map[string]string)
for file, sum := range inputs {
if strings.HasSuffix(file, ".go") || file == filepath.Join(root, "versions.json") || file == filepath.Join(root, "go", "go.mod") || file == filepath.Join(root, "go", "go.sum") {
@@ -140,7 +140,7 @@ func selectDependencyInputs(root string, inputs map[string]string, definition De
return relevant
}
func dependencyFingerprint(root string, inputs map[string]string, project string) string {
func dependencyFingerprint(root string, definitions []Definition, inputs map[string]string, project string) string {
definition := Definition{ProjectPath: project + "/" + project + ".csproj"}
for _, candidate := range definitions {
if candidate.Name() == project {
@@ -156,18 +156,22 @@ func dependencyFingerprint(root string, inputs map[string]string, project string
}
definition.UsesGameSdk = true
}
return digestInputs(selectDependencyInputs(root, inputs, definition))
return digestInputs(selectDependencyInputs(root, definitions, inputs, definition))
}
func developmentInputs(root, managed, bep string) ([]string, error) {
func developmentInputs(root, managed, bep string, registry Registry) ([]string, error) {
var files []string
tools := map[string]bool{}
for _, tool := range registry.Tools {
tools[filepath.Join(root, "plugins", filepath.Dir(filepath.FromSlash(tool.ProjectPath)))] = true
}
for _, directory := range []string{filepath.Join(root, "plugins"), filepath.Join(root, "go", "internal", "client", "plugin"), filepath.Join(root, "go", "internal", "buildversion")} {
err := filepath.WalkDir(directory, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
if entry.Name() == "bin" || entry.Name() == "obj" || entry.Name() == ".git" || entry.Name() == "CaptureEnvironment" || entry.Name() == "samples" {
if entry.Name() == "bin" || entry.Name() == "obj" || entry.Name() == ".git" || tools[path] || entry.Name() == "samples" {
return filepath.SkipDir
}
return nil
+6 -1
View File
@@ -28,6 +28,7 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
write("game/BrownDust II_Data/Managed/Assembly-CSharp.dll", "fixture")
write("game/BepInEx/core/BepInEx.dll", "fixture")
write("plugins/LocalIdentity/Plugin.cs", "fixture")
write(RegistryFile, `{"plugins":[{"id":"local_identity","project":"LocalIdentity/LocalIdentity.csproj","framework":"netstandard2.1","file":"BD2LocalIdentity.dll","version_key":"local_identity"}],"tools":[]}`)
write("go/internal/client/plugin/build.go", "fixture")
write("go/internal/buildversion/version.go", "fixture")
write("versions.json", "invalid JSON must not be read when cache is current")
@@ -49,7 +50,11 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
if work == "" {
t.Fatal("build did not establish a cache workspace")
}
inputs, err := snapshotInputs(root, filepath.Join(game, "BrownDust II_Data", "Managed"), filepath.Join(game, "BepInEx"), make(fileDigestCache))
registry, err := Load(root)
if err != nil {
t.Fatal(err)
}
inputs, err := snapshotInputs(root, filepath.Join(game, "BrownDust II_Data", "Managed"), filepath.Join(game, "BepInEx"), registry, make(fileDigestCache))
if err != nil {
t.Fatal(err)
}
+96 -32
View File
@@ -1,57 +1,90 @@
package plugin
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"bd2server/internal/common/util"
)
// RegistryFile lists every client plugin project. Adding a plugin only needs
// an entry here and its version in versions.json.
const RegistryFile = "plugins/registry.json"
type Definition struct {
ID, ProjectPath, Framework, FileName, VersionKey string
UsesGameSdk bool
SharedRuntime bool
Dependencies []string
ID string `json:"id"`
ProjectPath string `json:"project"`
Framework string `json:"framework"`
FileName string `json:"file"`
VersionKey string `json:"version_key,omitempty"`
UsesGameSdk bool `json:"game_sdk,omitempty"`
SharedRuntime bool `json:"shared_runtime,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}
var definitions = []Definition{
{ID: "game_names", ProjectPath: "GameNames/GameNames.csproj", Framework: "netstandard2.0", FileName: "BD2.GameNames.dll", SharedRuntime: true},
{ID: "local_identity", ProjectPath: "LocalIdentity/LocalIdentity.csproj", Framework: "netstandard2.1", FileName: "BD2LocalIdentity.dll", VersionKey: "local_identity", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "login_ui", ProjectPath: "LoginUI/LoginUI.csproj", Framework: "netstandard2.1", FileName: "BD2LoginUI.dll", VersionKey: "login_ui", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "cash_shop", ProjectPath: "CashShop/CashShop.csproj", Framework: "netstandard2.1", FileName: "BD2CashShop.dll", VersionKey: "cash_shop", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "fchat", ProjectPath: "FChat/FChat.csproj", Framework: "netstandard2.1", FileName: "BD2FChat.dll", VersionKey: "fchat", UsesGameSdk: true, Dependencies: []string{"game_names", "login_ui"}},
{ID: "fbattle", ProjectPath: "FBattle/FBattle.csproj", Framework: "netstandard2.1", FileName: "BD2FBattle.dll", VersionKey: "fbattle", UsesGameSdk: true, Dependencies: []string{"game_names", "local_identity"}},
{ID: "brown_dust_x_accel", ProjectPath: "BrownDustXAccel/BrownDustXAccel.csproj", Framework: "netstandard2.1", FileName: "BD2BrownDustXAccel.dll"},
// Tool is a C# project that is checked with the plugins but never shipped
// and never an input of the plugin build.
type Tool struct {
ProjectPath string `json:"project"`
}
func Definitions() []Definition {
out := slices.Clone(definitions)
for i := range out {
out[i].Dependencies = slices.Clone(out[i].Dependencies)
type Registry struct {
Plugins []Definition `json:"plugins"`
Tools []Tool `json:"tools"`
}
// Load reads and validates the plugin registry below the repository root.
func Load(root string) (Registry, error) {
var registry Registry
path := filepath.Join(root, filepath.FromSlash(RegistryFile))
raw, err := os.ReadFile(path)
if err != nil {
return registry, fmt.Errorf("clientplugin: read registry: %w", err)
}
return out
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&registry); err != nil {
return registry, fmt.Errorf("clientplugin: %s: %w", path, err)
}
if decoder.More() {
return registry, fmt.Errorf("clientplugin: %s must contain exactly one JSON object", path)
}
if err := registry.validate(); err != nil {
return registry, err
}
return registry, nil
}
func validateDefinitions() error {
byID := make(map[string]Definition, len(definitions))
outputs, projects := map[string]bool{}, map[string]bool{}
for _, d := range definitions {
func (r Registry) validate() error {
if len(r.Plugins) == 0 {
return errors.New("clientplugin: registry lists no plugins")
}
byID := make(map[string]Definition, len(r.Plugins))
outputs, projects, versionKeys := map[string]bool{}, map[string]bool{}, map[string]bool{}
for _, d := range r.Plugins {
if err := validateName(d.FileName); err != nil {
return err
}
if d.ID == "" || d.Name() == "" || d.ProjectPath == "" || filepath.IsAbs(d.ProjectPath) || strings.HasPrefix(filepath.Clean(d.ProjectPath), "..") {
if d.ID == "" || d.Framework == "" || !validProject(d.ProjectPath) {
return fmt.Errorf("clientplugin: invalid project definition %q", d.ID)
}
_, duplicate := byID[d.ID]
if duplicate || outputs[strings.ToLower(d.FileName)] || projects[d.Name()] {
if duplicate || outputs[strings.ToLower(d.FileName)] || projects[d.Name()] || d.VersionKey != "" && versionKeys[d.VersionKey] {
return fmt.Errorf("clientplugin: duplicate plugin definition %s", d.ID)
}
byID[d.ID], outputs[strings.ToLower(d.FileName)], projects[d.Name()] = d, true, true
byID[d.ID], outputs[strings.ToLower(d.FileName)], projects[d.Name()], versionKeys[d.VersionKey] = d, true, true, true
}
for _, tool := range r.Tools {
name := Definition{ProjectPath: tool.ProjectPath}.Name()
if !validProject(tool.ProjectPath) || projects[name] || name == "GameSdk" {
return fmt.Errorf("clientplugin: invalid tool project %q", tool.ProjectPath)
}
projects[name] = true
}
visited, visiting := map[string]bool{}, map[string]bool{}
var visit func(string) error
@@ -75,7 +108,7 @@ func validateDefinitions() error {
visiting[id], visited[id] = false, true
return nil
}
for _, d := range definitions {
for _, d := range r.Plugins {
if err := visit(d.ID); err != nil {
return err
}
@@ -83,6 +116,28 @@ func validateDefinitions() error {
return nil
}
func validProject(project string) bool {
clean := filepath.Clean(filepath.FromSlash(project))
return project != "" && strings.EqualFold(filepath.Ext(clean), ".csproj") && !filepath.IsAbs(clean) &&
clean != ".." && !strings.HasPrefix(clean, ".."+string(filepath.Separator)) && strings.Contains(filepath.ToSlash(clean), "/")
}
// Project is one C# project the repository checks.
type Project struct{ Name, File string }
// Projects lists every C# project in check order: the shared SDK, the tools,
// then the plugins.
func (r Registry) Projects(root string) []Project {
projects := []Project{{"GameSdk", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj")}}
for _, tool := range r.Tools {
projects = append(projects, Project{Definition{ProjectPath: tool.ProjectPath}.Name(), filepath.Join(root, "plugins", filepath.FromSlash(tool.ProjectPath))})
}
for _, d := range r.Plugins {
projects = append(projects, Project{d.Name(), d.ProjectFile(root)})
}
return projects
}
func (d Definition) Name() string {
return strings.TrimSuffix(filepath.Base(d.ProjectPath), filepath.Ext(d.ProjectPath))
}
@@ -95,7 +150,7 @@ func (d Definition) Output(root string) string {
return filepath.Join(filepath.Dir(d.ProjectFile(root)), "bin", "Release", d.Framework, d.FileName)
}
func (d Definition) dependencyProjects() map[string]bool {
func (d Definition) dependencyProjects(definitions []Definition) map[string]bool {
projects := map[string]bool{d.Name(): true}
var visit func(Definition)
visit = func(current Definition) {
@@ -112,9 +167,9 @@ func (d Definition) dependencyProjects() map[string]bool {
return projects
}
func verifyDependencyOutputs(root string) error {
func verifyDependencyOutputs(root string, definitions []Definition) error {
for _, d := range definitions {
projects := d.dependencyProjects()
projects := d.dependencyProjects(definitions)
for _, dependency := range definitions {
if !dependency.SharedRuntime || d.ID == dependency.ID || !projects[dependency.Name()] {
continue
@@ -141,9 +196,18 @@ type Artifact struct {
type Set []Artifact
func Development(root string) Set {
set := make(Set, 0, len(definitions))
for _, d := range definitions {
// Development lists the plugin outputs built from the repository at root.
func Development(root string) (Set, error) {
registry, err := Load(root)
if err != nil {
return nil, err
}
return registry.Development(root), nil
}
func (r Registry) Development(root string) Set {
set := make(Set, 0, len(r.Plugins))
for _, d := range r.Plugins {
set = append(set, Artifact{ID: d.ID, Name: d.FileName, Source: d.Output(root), VersionKey: d.VersionKey})
}
return set
+19 -37
View File
@@ -5,6 +5,7 @@ package versionconfig
import (
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"regexp"
@@ -20,6 +21,7 @@ var (
semanticVersion = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
releaseVersion = regexp.MustCompile(`^([0-9]+\.[0-9]+\.[0-9]+)\+(client|server)\.([0-9]+\.[0-9]+\.[0-9]+)$`)
resourceVersion = regexp.MustCompile(`^[0-9]{14}$`)
pluginKey = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
currentMu sync.RWMutex
current *Config
)
@@ -40,14 +42,9 @@ type Config struct {
SourcePath string `json:"-"`
}
type PluginVersions struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
// PluginVersions maps each plugin's version key (see plugins/registry.json)
// to its three-part version.
type PluginVersions map[string]string
// Load reads one explicit version file. Unknown fields and trailing JSON are
// rejected so a misspelled version key cannot silently select stale data.
@@ -74,25 +71,23 @@ func GameData() string { return Current().GameDataVersion }
func Bundle() string { return Current().BundleVersion }
func (c Config) Validate() error {
for name, value := range map[string]string{
"game_version": c.GameVersion,
"plugins.local_identity": c.Plugins.LocalIdentity,
"plugins.capture_environment": c.Plugins.CaptureEnvironment,
"plugins.login_ui": c.Plugins.LoginUI,
"plugins.fchat": c.Plugins.FChat,
} {
if !semanticVersion.MatchString(value) {
return fmt.Errorf("%s must be a numeric three-part version", name)
if !semanticVersion.MatchString(c.GameVersion) {
return errors.New("game_version must be a numeric three-part version")
}
if len(c.Plugins) == 0 {
return errors.New("plugins must list at least one plugin version")
}
for id, version := range c.Plugins {
if !pluginKey.MatchString(id) || !semanticVersion.MatchString(version) {
return fmt.Errorf("plugins.%s must be a numeric three-part version", id)
}
}
for id, pair := range c.Plugins.pairs(c.MinimumPlugins) {
if !semanticVersion.MatchString(pair[1]) || compareSemantic(pair[1], pair[0]) > 0 {
for id, minimum := range c.MinimumPlugins {
current, found := c.Plugins[id]
if !found || !semanticVersion.MatchString(minimum) || compareSemantic(minimum, current) > 0 {
return fmt.Errorf("minimum_plugins.%s must be a numeric three-part version no newer than plugins.%s", id, id)
}
}
if c.Plugins.FBattle != "" && !semanticVersion.MatchString(c.Plugins.FBattle) {
return errors.New("plugins.fbattle must be a numeric three-part version")
}
if err := validateReleaseVersion("client_version", c.ClientVersion, c.GameVersion, "client"); err != nil {
return err
}
@@ -116,22 +111,9 @@ func (c Config) Validate() error {
return nil
}
// ByID lists the plugin versions under their versions.json keys.
// ByID returns a copy of the versions under their versions.json keys.
func (p PluginVersions) ByID() map[string]string {
versions := map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
if p.FBattle != "" {
versions["fbattle"] = p.FBattle
}
return versions
}
func (p PluginVersions) pairs(minimum PluginVersions) map[string][2]string {
current, lowest := p.ByID(), minimum.ByID()
out := map[string][2]string{}
for id, version := range current {
out[id] = [2]string{version, lowest[id]}
}
return out
return maps.Clone(map[string]string(p))
}
func compareSemantic(a, b string) int {
@@ -0,0 +1,6 @@
{
"life.batch.remove_name": "{0} selected objects",
"life.batch.remove_blocked": "Some of the selected objects cannot be removed.",
"life.batch.rotate_outside": "Rotating would move objects outside the placeable area.",
"experience.friend.online": "Online"
}
@@ -0,0 +1,6 @@
{
"life.batch.remove_name": "選択中の {0} 個のオブジェクト",
"life.batch.remove_blocked": "選択中に撤去できないオブジェクトがあります。",
"life.batch.rotate_outside": "回転すると配置可能な範囲からはみ出します。",
"experience.friend.online": "オンライン"
}
@@ -0,0 +1,6 @@
{
"life.batch.remove_name": "선택한 오브젝트 {0}개",
"life.batch.remove_blocked": "선택한 오브젝트 중 철거할 수 없는 오브젝트가 있습니다.",
"life.batch.rotate_outside": "회전하면 배치 가능한 범위를 벗어납니다.",
"experience.friend.online": "온라인"
}
@@ -0,0 +1,6 @@
{
"life.batch.remove_name": "已选择的 {0} 个物件",
"life.batch.remove_blocked": "所选物件中有无法拆除的物件。",
"life.batch.rotate_outside": "旋转后会超出可放置的范围。",
"experience.friend.online": "在线"
}
@@ -0,0 +1,6 @@
{
"life.batch.remove_name": "已選擇的 {0} 個物件",
"life.batch.remove_blocked": "所選物件中有無法拆除的物件。",
"life.batch.rotate_outside": "旋轉後會超出可放置的範圍。",
"experience.friend.online": "線上"
}
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<AssemblyName>BD2BetterExperience</AssemblyName>
<RootNamespace>Bd2BetterExperience</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>better_experience</BD2PluginVersionKey>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include="../Shared/ClientSettings.cs" Link="Shared/ClientSettings.cs" />
<Reference Include="Newtonsoft.Json"><HintPath>$(BD2ManagedDir)/Newtonsoft.Json.dll</HintPath><Private>false</Private></Reference>
<Reference Include="BepInEx"><HintPath>$(BD2BepInExDir)/core/BepInEx.dll</HintPath><Private>false</Private></Reference>
<Reference Include="0Harmony"><HintPath>$(BD2BepInExDir)/core/0Harmony.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Google.Protobuf"><HintPath>$(BD2ManagedDir)/Google.Protobuf.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Unity.TextMeshPro"><HintPath>$(BD2ManagedDir)/Unity.TextMeshPro.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine"><HintPath>$(BD2ManagedDir)/UnityEngine.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.CoreModule"><HintPath>$(BD2ManagedDir)/UnityEngine.CoreModule.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.UI"><HintPath>$(BD2ManagedDir)/UnityEngine.UI.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.UIModule"><HintPath>$(BD2ManagedDir)/UnityEngine.UIModule.dll</HintPath><Private>false</Private></Reference>
</ItemGroup>
</Project>
@@ -3,16 +3,18 @@ using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using BD2.GameNames;
using BepInEx.Logging;
using HarmonyLib;
namespace Bd2LocalIdentity;
namespace Bd2BetterExperience.Housing;
internal static class RoomPlacementStability
internal sealed class RoomPlacementStability : IModule
{
private static MethodInfo IsHideGetter;
internal static void Install(Harmony harmony, ManualLogSource logger)
public string Id => "RoomPlacementStability";
public string Description => "Handle empty walls safely when placing the first room board skin.";
public void Install(Harmony harmony)
{
Type stateMachine = Game.FindType("MyRoom/<SetupBoardSkinObjectAsync>d__50")
?? throw new MissingMemberException("MyRoom board-skin setup state machine is unavailable");
@@ -23,7 +25,7 @@ internal static class RoomPlacementStability
IsHideGetter = boardSkin.GetGameProperty("IsHide", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetMethod
?? throw new MissingMethodException("MyRoomObjectBoardSkin.IsHide is unavailable");
harmony.Patch(moveNext, transpiler: new HarmonyMethod(typeof(RoomPlacementStability), nameof(NullSafeBoardSkinVisibility)));
logger.LogInfo("MyRoom placement tolerates an empty wall before the first board skin");
Plugin.Log.LogInfo("MyRoom placement tolerates an empty wall before the first board skin");
}
private static bool SafeIsHidden(object boardSkin)
@@ -0,0 +1,368 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using BD2.GameNames;
using FieldEvent.Common;
using FieldEvent.Life;
using FieldEvent.Life.Chunk;
using HarmonyLib;
using Proto.Design.common;
using Proto.Net;
using UnityEngine;
using UnityEngine.EventSystems;
using TextComponent = BD2.GameSdk.Component;
namespace Bd2BetterExperience.Life;
// The farm editor's multi-select can only move the selection. This module
// gives it the single selection's rotate and remove buttons: rotate turns the
// whole selection a quarter turn about its centre, remove takes every
// selected object off the farm after one confirmation.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal sealed class LifeBatchEdit : IModule
{
private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const int ItemObject = 1, BuildingObject = 3, DecorationObject = 4, ExchangeItem = 64;
private const int BelowMinimumText = 160079, InventoryFullText = 160074;
private static Group group;
public string Id => "LifeBatchEdit";
public string Description => "Rotate and remove a multi-selection in the farm editor.";
public void Install(Harmony harmony)
{
Type ui = typeof(AvatarLifeHousingEditUI_EditUI);
harmony.Patch(Method(ui, "SetMultipleSelectedLPOs"), postfix: Hook(nameof(Selected)));
harmony.Patch(Method(ui, "ClearMultiState"), postfix: Hook(nameof(Cleared)));
harmony.Patch(Method(ui, "OnClickUI"), prefix: Hook(nameof(Click)));
harmony.Patch(Method(ui, "OnDragMultiple"), prefix: Hook(nameof(Drag)));
harmony.Patch(Method(ui, "OnClickConfirmMulti"), prefix: Hook(nameof(Confirm)));
harmony.Patch(Method(ui, "OnClickCancelMulti"), prefix: Hook(nameof(Cancel)));
}
private static MethodInfo Method(Type owner, string name) =>
owner.GetGameMethod(name, Fields | BindingFlags.DeclaredOnly) ?? throw new MissingMethodException(owner.Name, name);
private static HarmonyMethod Hook(string name) => new(typeof(LifeBatchEdit), name);
private static T Get<T>(object owner, string name) => (T)(owner.GetType().GetGameField(name, Fields) ??
throw new MissingFieldException(owner.GetType().Name, name)).GetValue(owner);
private static void Set(object owner, string name, object value) => (owner.GetType().GetGameField(name, Fields) ??
throw new MissingFieldException(owner.GetType().Name, name)).SetValue(owner, value);
private static object Call(object owner, string name, params object[] arguments) =>
Method(owner.GetType(), name).Invoke(owner, arguments);
private static string Text(string key) => TextComponent.Translatable(key).GetString();
// Native multi-select state, read straight from the editor.
private sealed class Group(AvatarLifeHousingEditUI_EditUI ui)
{
internal AvatarLifeHousingEditUI_EditUI UI { get; } = ui;
internal List<LifePlaceableObject> Objects => Get<List<LifePlaceableObject>>(UI, "_multiSelectedLPOs");
internal List<PlacementData> Originals => Get<List<PlacementData>>(UI, "_multiOriginalPlacements");
internal List<Vector2Int> Offsets => Get<List<Vector2Int>>(UI, "_multiRelativeCellOffsets");
internal LifeChunkController Chunks => Get<LifeChunkController>(UI, "_chunkController");
internal AvatarLifeHousingEditUI Parent => Get<AvatarLifeHousingEditUI>(UI, "_parentUI");
internal Vector2Int Center { get => Get<Vector2Int>(UI, "_currentGroupCenterCell"); set => Set(UI, "_currentGroupCenterCell", value); }
// Each object's rotation once the quarter turns are applied; while it
// matches the originals the game's own move code still applies.
internal List<int> Rotations { get; } = [];
internal bool Turned { get; set; }
}
private static void Selected(AvatarLifeHousingEditUI_EditUI __instance)
{
group = null;
try
{
var current = new Group(__instance);
if (current.Chunks == null || current.Objects.Count == 0) return;
current.Rotations.AddRange(current.Originals.Select(placement => placement.rotation));
group = current;
ButtonOnOffComponent rotate = Get<ButtonOnOffComponent>(__instance, "_rotateBtn");
rotate.gameObject.SetActive(true);
rotate.Set(current.Objects.Any(item => item != null && item.RotationType > RotationType.NoRotation));
// The removal buttons have no disabled look (Set(false) hides them),
// so the one shown stays enabled and a refusal explains itself on click.
RemoveButton(__instance, current.Objects).Set(true);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit selection: " + error); }
}
// The game's own button for removing this kind of object: put away for
// items, demolish for buildings, delete for decorations. A mixed
// selection uses demolish.
private static ButtonOnOffComponent RemoveButton(AvatarLifeHousingEditUI_EditUI ui, IList<LifePlaceableObject> objects)
{
int[] types = [.. objects.Select(item => item?.DBInfo == null ? 0 : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId)?.ObjectType ?? 0).Distinct()];
return Get<ButtonOnOffComponent>(ui, types.Length != 1 ? "_demolishBtn" : types[0] switch
{
ItemObject => "_invenBtn",
DecorationObject => "_deleteBtn",
_ => "_demolishBtn",
});
}
private static void Cleared(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI == __instance) group = null;
}
private static bool Click(AvatarLifeHousingEditUI_EditUI __instance, GameObject __0, ref bool __result)
{
if (group?.UI != __instance || __0 == null || !Get<bool>(__instance, "_isMultiMode")) return true;
try
{
if (__0 == Get<ButtonOnOffComponent>(__instance, "_rotateBtn").gameObject) { Rotate(group); __result = true; return false; }
if (__0 == RemoveButton(__instance, group.Objects).gameObject) { Remove(group); __result = true; return false; }
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit click: " + error); __result = true; return false; }
return true;
}
// Quarter turn clockwise. Footprints turn about their anchors through
// ApplyRotationOrFlip (x, z) -> (z, -x), so the anchors' offsets from the
// group centre turn the same way and the layout stays rigid.
private static void Rotate(Group current)
{
GroundChunkManager chunks = current.Chunks.GetChunkManager();
if (chunks == null) return;
List<Vector2Int> offsets = current.Offsets;
var turned = offsets.Select(offset => new Vector2Int(offset.y, -offset.x)).ToList();
foreach (Vector2Int offset in turned)
{
Vector2Int cell = current.Center + offset;
if (!chunks.GetCellAtWorldCell(cell.x, cell.y).isValid) { UIManager.OpenBarNotice(Text("life.batch.rotate_outside"), false, null); return; }
}
List<LifePlaceableObject> objects = current.Objects;
for (int i = 0; i < objects.Count; i++)
{
offsets[i] = turned[i];
LifePlaceableObject item = objects[i];
if (item != null && item.RotationType > RotationType.NoRotation) current.Rotations[i] = item.GetNextRotation(current.Rotations[i]);
}
current.Turned = true;
Get<IndexedCommonSoundEmitter>(current.UI, "_moveCellSoundEmitter")?.PlayManualIndexiedCommonSound();
Show(current, chunks);
}
// The game's drag, with the group's own rotations instead of the originals.
private static bool Drag(AvatarLifeHousingEditUI_EditUI __instance, PointerEventData __0)
{
if (group?.UI != __instance || !group.Turned) return true;
try
{
var world = (Vector3)Call(__instance, "ScreenToWorldPosition", (Vector3)__0.position);
if (world == Vector3.zero) return false;
var center = (Vector2Int)Call(__instance, "WorldPositionToWorldCellDirect", world);
if (center == group.Center) return false;
GroundChunkManager chunks = group.Chunks.GetChunkManager();
if (chunks == null) return false;
foreach (Vector2Int offset in group.Offsets)
{
Vector2Int cell = center + offset;
if (!chunks.GetCellAtWorldCell(cell.x, cell.y).isValid) return false;
}
Get<IndexedCommonSoundEmitter>(__instance, "_moveCellSoundEmitter")?.PlayManualIndexiedCommonSound();
group.Center = center;
Show(group, chunks);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit drag: " + error); }
return false;
}
// Places every object at the group centre with its current rotation and
// checks the result as OnDragMultiple does.
private static void Show(Group current, GroundChunkManager chunks)
{
List<LifePlaceableObject> objects = current.Objects;
List<PlacementData> originals = current.Originals;
List<Vector2Int> offsets = current.Offsets;
for (int i = 0; i < objects.Count; i++)
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], false, originals[i].rotation, 0);
bool valid = true;
var occupied = new HashSet<long>();
for (int i = 0; i < objects.Count; i++)
{
Vector2Int cell = current.Center + offsets[i];
CellInfo anchor = chunks.GetCellAtWorldCell(cell.x, cell.y);
int rotation = current.Rotations[i];
LifePlaceableObject item = objects[i];
item.transform.position = chunks.GetCellWorldPosition(anchor.chunkId, anchor.localX, anchor.localY, item, rotation);
item.ApplyVisualRotation(rotation);
item.UpdatePlacementPreview(chunks, anchor, rotation);
if (!(bool)Call(current.UI, "CheckPlacementValidForLPO", chunks, item, anchor, rotation)) valid = false;
if (valid && !(bool)Call(current.UI, "CollectOccupiedWorldCells", chunks, item, anchor, rotation, occupied)) valid = false;
}
for (int i = 0; i < objects.Count; i++)
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], true, originals[i].rotation, objects[i].LpoId);
Set(current.UI, "_isCurrentPlacementValid", valid);
Get<ButtonOnOffComponent>(current.UI, "_checkBtn")?.Set(valid);
Call(current.UI, "UpdateEditMenuPositionMulti");
}
// OnClickConfirmMulti with the group's rotations. A turned group no longer
// moves by one shared delta, so it saves every object's own position.
private static bool Confirm(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI != __instance || !group.Turned) return true;
Group current = group;
try
{
if (!Get<bool>(__instance, "_isCurrentPlacementValid")) return false;
LifeChunkController controller = current.Chunks;
GroundChunkManager chunks = controller?.GetChunkManager();
if (chunks == null) return false;
List<LifePlaceableObject> objects = current.Objects;
List<PlacementData> originals = current.Originals;
for (int i = 0; i < objects.Count; i++)
{
if (objects[i] == null || objects[i].IsTemporaryBuilding) continue;
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], false, originals[i].rotation, 0);
}
for (int i = 0; i < objects.Count; i++)
{
if (objects[i] == null) continue;
Vector2Int cell = current.Center + current.Offsets[i];
objects[i].HidePlacementPreview();
new ConfirmPlacementEvent(objects[i], originals[i], chunks.GetCellAtWorldCell(cell.x, cell.y), current.Rotations[i], null, true).Send();
}
var saved = new List<LifePlaceableObject>(objects);
var keys = saved.Select(item => item?.DBInfo != null ? new PlacedObjectKey(item.ChunkIDDBInfo, item.DBInfo.ObjectId, item.DBInfo.X, item.DBInfo.Y) : default).ToList();
bool delta = LifePacket.UseDeltaPositionSave;
LifePacket.UseDeltaPositionSave = false;
try { LifePacket.SendLifeWorldObjectPositionSave(saved, () => controller.ReKeyPlacedObjects(saved, keys)); }
finally { LifePacket.UseDeltaPositionSave = delta; }
AvatarLifeHousingEditUI parent = current.Parent;
if (parent != null) { parent.RefreshBuildList(); parent.ClearSelectionHighlight(); }
Call(__instance, "ClearMultiState");
__instance.SetActive(false);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit confirm: " + error); }
return false;
}
// Cancel restores positions; turn the objects back before it does.
private static void Cancel(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI != __instance || !group.Turned) return;
try
{
List<LifePlaceableObject> objects = group.Objects;
List<PlacementData> originals = group.Originals;
for (int i = 0; i < objects.Count; i++) if (objects[i] != null) objects[i].ApplyVisualRotation(originals[i].rotation);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit cancel: " + error); }
}
// The single selection's delete rules, applied to the whole selection:
// only placed items, buildings and decorations, never below a group's
// minimum count, and never refunding past an item's stack limit.
private static bool Removable(IList<LifePlaceableObject> objects, out int notice)
{
notice = 0;
var removed = new Dictionary<LifeObjectGroupTable, int>();
var refunds = new Dictionary<int, int>();
foreach (LifePlaceableObject item in objects)
{
LifeObjectGroupTable table = item == null || item.IsTemporaryBuilding || item.DBInfo == null ? null : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId);
if (table == null || table.ObjectType is not (ItemObject or BuildingObject or DecorationObject)) return false;
removed[table] = removed.TryGetValue(table, out int count) ? count + 1 : 1;
if (table.ObjectType != BuildingObject) continue;
LifeBuildingObjectTable building = LifeInfo.GetLifeBuildingObjectTable(table.Id);
if (building == null) continue;
for (int i = 0; i < building.RequireItemType.Count; i++)
{
if (building.RequireItemType[i] == ExchangeItem) continue;
int id = building.RequireItemId[i];
refunds[id] = (refunds.TryGetValue(id, out int total) ? total : 0) + building.RequireItemCount[i];
}
}
foreach (KeyValuePair<LifeObjectGroupTable, int> pair in removed)
if (pair.Key.MinCount > 0 && LifePacket.GetLifeWorldObjectDbList(pair.Key.Id).Count - pair.Value < pair.Key.MinCount) { notice = BelowMinimumText; return false; }
foreach (KeyValuePair<int, int> pair in refunds)
if (LifePacket.GetItemInfoCount(pair.Key) + pair.Value > LifeInfo.GetLifeItemTable(pair.Key).StackCount) { notice = InventoryFullText; return false; }
return true;
}
private static void Remove(Group current)
{
var objects = current.Objects.Where(item => item != null).ToList();
if (objects.Count == 0) return;
if (!Removable(objects, out int notice))
{
UIManager.OpenBarNotice(notice != 0 ? LocalTextInfo.GetText(notice) : Text("life.batch.remove_blocked"), false, null);
return;
}
string title = string.Format(CultureInfo.CurrentCulture, Text("life.batch.remove_name"), objects.Count);
LifePlaceableObject[] returned = [.. objects.Where(item => Table(item)?.ObjectType is ItemObject or BuildingObject)];
if (returned.Length == 0)
{
// Decorations give nothing back; the game's own delete warning says so.
UIManager.AddUI<AvatarLifeItemDeletePopupUI>(popup =>
{
popup.SetUI(title, () => RemoveAll(current, objects));
// One confirmation covers the whole batch, so never offer to skip it.
Get<ButtonOnOffComponent>(popup, "_todayOnOffButton")?.gameObject.SetActive(false);
});
return;
}
UIManager.AddUI<AvatarLifeBuildDeletePopupUI>(popup => ShowReturns(popup, title, returned, () => RemoveAll(current, objects)));
}
private static LifeObjectGroupTable Table(LifePlaceableObject item) =>
item == null || item.DBInfo == null ? null : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId);
// The game's demolish popup, filled with everything the batch gives back:
// each building's materials and each put-away item, totalled per kind.
private static void ShowReturns(AvatarLifeBuildDeletePopupUI popup, string title, IList<LifePlaceableObject> returned, Action confirm)
{
LifePlaceableObject first = returned[0];
popup.SetUI(first.DBInfo.ObjectId, first.DBInfo.Index, confirm);
var totals = new Dictionary<(Define_LifeObjectType Kind, int Type, int Id), int>();
void add(Define_LifeObjectType kind, int type, int id, int count) =>
totals[(kind, type, id)] = (totals.TryGetValue((kind, type, id), out int total) ? total : 0) + count;
string info = LocalTextInfo.GetText(160073);
var notes = new HashSet<int>();
foreach (LifePlaceableObject item in returned)
{
LifeObjectGroupTable table = Table(item);
if (table.ObjectType == ItemObject) { add(Define_LifeObjectType.LifeCraftingObject, 0, table.Id, 1); continue; }
LifeBuildingObjectTable building = LifeInfo.GetLifeBuildingObjectTable(table.Id);
if (building == null) continue;
for (int i = 0; i < building.RequireItemType.Count; i++)
add(Define_LifeObjectType.LifeBuildingObject, building.RequireItemType[i], building.RequireItemId[i], building.RequireItemCount[i]);
// Same warnings as demolishing one helper house that is in use.
if (building.FunctionType == 101 && LifePacket.GetLifeHelperDBInfo(item.DBInfo.Index) != null) notes.Add(160262);
else if (building.FunctionType == 101 && LifePacket.GetLifeHelperGachaDBInfo(item.DBInfo.Index) != null) notes.Add(160254);
}
foreach (int note in notes.OrderBy(note => note)) info += "\n\n" + LocalTextInfo.GetText(note);
int index = 0;
foreach (KeyValuePair<(Define_LifeObjectType Kind, int Type, int Id), int> entry in totals)
Call(popup, "AddIcon", index++, entry.Key.Kind, entry.Key.Type, entry.Key.Id, entry.Value);
List<AvatarLifeBuildDeletePopupUI_ScrollItem> icons = Get<List<AvatarLifeBuildDeletePopupUI_ScrollItem>>(popup, "_itemList");
for (int i = index; i < icons.Count; i++) icons[i].gameObject.SetActive(false);
Get<TMPro.TMP_Text>(popup, "_textName").SetText(title, true);
Get<TMPro.TMP_Text>(popup, "_textInfo").text = info;
}
private static void RemoveAll(Group current, List<LifePlaceableObject> objects)
{
AvatarLifeHousingEditUI parent = current.Parent;
// Put the selection back where it was, then remove one object at a
// time so each unplace finishes before the next starts.
Call(current.UI, "OnClickCancelMulti", false);
void Next(int index)
{
while (index < objects.Count && objects[index] == null) index++;
if (index >= objects.Count) { if (parent != null) parent.RefreshBuildList(); return; }
new DeletePlacementEvent(objects[index], () => Next(index + 1)).Send();
}
Next(0);
}
}
@@ -0,0 +1,41 @@
using System.Runtime.CompilerServices;
using BD2.GameNames;
using BDNetwork;
using Google.Protobuf;
using HarmonyLib;
using Proto.Design.common;
using Proto.Net;
namespace Bd2BetterExperience.Life;
internal sealed class LifeMinimumBuildings : IModule
{
private const int RemoveMinimumField = 100;
private static readonly ConditionalWeakTable<LifeWorldObjectUnplaceSaveRequest, object> marked = [];
public string Id => "LifeMinimumBuildings";
public string Description => "Allow farm buildings to be removed below their minimum count. Requires server support.";
public void Install(Harmony harmony)
{
harmony.Patch(Game.Getter<LifeObjectGroupTable, int>(table => table.MinCount),
postfix: new HarmonyMethod(typeof(LifeMinimumBuildings), nameof(Minimum)));
harmony.Patch(Game.Method<NetworkManager>(network => network.Send(null, null, true, null, false, null)),
prefix: new HarmonyMethod(typeof(LifeMinimumBuildings), nameof(BeforeSend)));
}
private static void Minimum(ref int __result) => __result = 0;
private static void BeforeSend(IMessage __0)
{
if (__0 is not LifeWorldObjectUnplaceSaveRequest request || marked.TryGetValue(request, out _)) return;
byte[] envelope = new byte[CodedOutputStream.ComputeTagSize(RemoveMinimumField) + 1];
using (var output = new CodedOutputStream(envelope))
{
output.WriteTag(RemoveMinimumField, WireFormat.WireType.Varint);
output.WriteBool(true);
}
request.MergeFrom(envelope);
marked.Add(request, new object());
}
}
@@ -6,17 +6,20 @@ using Proto.Net;
using gamfs;
using static BD2.GameNames.Game;
namespace Bd2LocalIdentity;
namespace Bd2BetterExperience.Navigation;
// Cancel the leftover arrival callback after a commission is turned in manually;
// the game's ClearQuestNav(false) would otherwise replay its dialogue.
internal static class CommissionNavigation
internal sealed class CommissionNavigation : IModule
{
private static ManualLogSource Log;
internal static void Install(Harmony harmony, ManualLogSource logger)
public string Id => "CommissionNavigation";
public string Description => "Stop completed manual-talk commissions from replaying navigation dialogue.";
public void Install(Harmony harmony)
{
Log = logger;
Log = Plugin.Log;
MethodInfo target = typeof(QuestPacket).GetGameMethod("RefreshQuestNavOnQuestClear", BindingFlags.Static | BindingFlags.NonPublic);
harmony.Patch(target, prefix: new HarmonyMethod(typeof(CommissionNavigation), nameof(CancelCompletedTalkDestination)));
}
@@ -1,65 +1,17 @@
using System;
using Bd2.Client;
using BD2.GameNames;
using static BD2.GameNames.Game;
using System.Reflection;
using BepInEx.Logging;
using BD2.GameNames;
using HarmonyLib;
using UnityEngine;
namespace Bd2LocalIdentity;
namespace Bd2BetterExperience.Performance;
internal static class ClientPresentation
internal sealed class PerformanceOverlay : IModule
{
private static ManualLogSource Log;
private static MethodInfo SwitchToFullScreenMethod;
internal static void Initialize(ManualLogSource logger) => Log = logger;
public string Id => "PerformanceOverlay";
public string Description => "Hide the native FPS performance overlay.";
internal static void InstallStartupFullscreen(Harmony harmony, Type appManager)
{
if (ClientSettings.CurrentInstance != null)
{
Log?.LogInfo("Client instance startup respects launcher window parameters");
return;
}
MethodInfo initializeResolution = appManager?.GetGameMethod(
"InitPCResolution",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
Type.EmptyTypes,
null);
SwitchToFullScreenMethod = appManager?.GetGameMethod(
nameof(AppManager.SwitchToFullScreen),
BindingFlags.Instance | BindingFlags.Public,
null,
[typeof(bool)],
null);
if (initializeResolution == null || SwitchToFullScreenMethod == null)
{
throw new MissingMethodException("AppManager fullscreen methods were not found (client version mismatch)");
}
harmony.Patch(
initializeResolution,
postfix: new HarmonyMethod(typeof(ClientPresentation), nameof(InitializeResolutionPostfix)));
Log?.LogInfo("Native startup fullscreen patch installed");
}
private static void InitializeResolutionPostfix(object __instance)
{
try
{
// Use the game's own FullScreenWindow path so the behaviour is
// identical on Windows and macOS. This runs once during startup;
// later user-initiated switches to windowed mode remain intact.
SwitchToFullScreenMethod?.Invoke(__instance, [false]);
}
catch (Exception ex)
{
Log?.LogError("Could not apply native startup fullscreen: " + ex);
}
}
internal static void InstallPerformanceOverlaySuppression(Harmony harmony)
public void Install(Harmony harmony)
{
Type fpsCheck = typeof(FPS_Check);
MethodInfo start = fpsCheck?.GetGameMethod(
@@ -91,13 +43,13 @@ internal static class ClientPresentation
throw new MissingMethodException("FPS_Check overlay methods were not found (client version mismatch)");
}
var skip = new HarmonyMethod(typeof(ClientPresentation), nameof(SkipPerformanceOverlay));
var hide = new HarmonyMethod(typeof(ClientPresentation), nameof(HidePerformanceOverlayPostfix));
var skip = new HarmonyMethod(typeof(PerformanceOverlay), nameof(SkipPerformanceOverlay));
var hide = new HarmonyMethod(typeof(PerformanceOverlay), nameof(HidePerformanceOverlayPostfix));
harmony.Patch(start, prefix: skip);
harmony.Patch(render, prefix: skip);
harmony.Patch(onEnable, postfix: hide);
harmony.Patch(onInitialize, postfix: hide);
Log?.LogInfo("FPS_Check performance overlay disabled");
Plugin.Log?.LogInfo("FPS_Check performance overlay disabled");
}
private static bool SkipPerformanceOverlay(object __instance)
@@ -145,7 +97,7 @@ internal static class ClientPresentation
}
catch (Exception ex)
{
Log?.LogError("Could not suppress FPS_Check overlay: " + ex);
Plugin.Log?.LogError("Could not suppress FPS_Check overlay: " + ex);
}
}
+71
View File
@@ -0,0 +1,71 @@
using System;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Bd2BetterExperience.Life;
using Bd2BetterExperience.Window;
using Bd2BetterExperience.Performance;
using Bd2BetterExperience.Social;
using Bd2BetterExperience.Rewards;
using Bd2BetterExperience.Housing;
using Bd2BetterExperience.Navigation;
namespace Bd2BetterExperience;
// Quality-of-life additions to the game's own screens. Each module is
// independent and can be turned off in the plugin's BepInEx config.
[BepInPlugin(PluginId, Name, Version)]
public sealed class Plugin : BaseUnityPlugin
{
public const string PluginId = "bd2.betterexperience";
public const string Name = "BD2 Better Experience";
public const string Version = Bd2Build.Versions.Plugin;
internal static ManualLogSource Log;
internal static ConfigFile Settings;
private static readonly IModule[] Modules = [
new LifeBatchEdit(),
new LifeMinimumBuildings(),
new WindowPreferences(),
new PerformanceOverlay(),
new FriendPresence(),
new PassRewardPresentation(),
new RoomPlacementStability(),
new CommissionNavigation()
];
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes this lifecycle callback.")]
private void Awake()
{
Log = Logger;
Settings = Config;
foreach (IModule module in Modules)
{
ConfigEntry<bool> enabled = Config.Bind("Modules", module.Id, true, module.Description);
if (!enabled.Value) { Logger.LogInfo(module.Id + " disabled"); continue; }
// Each module patches under its own id so one failing leaves the others in place.
#pragma warning disable CA2000
var harmony = new Harmony(PluginId + "." + module.Id);
#pragma warning restore CA2000
try
{
module.Install(harmony);
Logger.LogInfo(module.Id + " installed");
}
catch (Exception error)
{
harmony.UnpatchSelf();
Logger.LogError(module.Id + " failed to install: " + error);
}
}
}
}
internal interface IModule
{
// The config key under [Modules].
string Id { get; }
string Description { get; }
void Install(Harmony harmony);
}
@@ -6,11 +6,11 @@ using System.Reflection;
using BD2.GameNames;
using HarmonyLib;
namespace Bd2CashShop;
namespace Bd2BetterExperience.Rewards;
// Native pass callbacks save rewards but discard their presentation list.
// Capture that list after the native save and feed it to the native popup.
internal static class PassRewardPresentation
internal sealed class PassRewardPresentation : IModule
{
private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
[ThreadStatic] private static Capture current;
@@ -26,7 +26,10 @@ internal static class PassRewardPresentation
internal readonly List<ItemBaseInfo> Rewards = [];
}
internal static void Install(Harmony harmony)
public string Id => "PassRewardPresentation";
public string Description => "Show pass rewards and merge their presentation when collecting all.";
public void Install(Harmony harmony)
{
MethodInfo receiver = typeof(MissionPassPacket).GetNestedTypes(All)
.SelectMany(type => type.GetMethods(All | BindingFlags.DeclaredOnly))
@@ -6,14 +6,17 @@ using gamfs;
using TMPro;
using TextComponent = BD2.GameSdk.Component;
namespace Bd2FChat;
namespace Bd2BetterExperience.Social;
internal static class FriendPresence
internal sealed class FriendPresence : IModule
{
private static FieldInfo friendInfo;
private static FieldInfo introduction;
internal static void Install(Harmony harmony)
public string Id => "FriendPresence";
public string Description => "Show a green online indicator in the friend list.";
public void Install(Harmony harmony)
{
const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic;
friendInfo = typeof(FriendItem).GetGameField("_friendInfoData", fields)
@@ -31,7 +34,7 @@ internal static class FriendPresence
var label = introduction.GetValue(__instance) as TMP_Text;
if (label == null || SG.Time.UnixTimeStampToDateTime(info.LastLoginDate) <= SG.Time.Now()) return true;
label.richText = true;
label.text = "<color=#63D189>● " + TextComponent.Translatable("fchat.friend.online").GetString() + "</color>";
label.text = "<color=#63D189>● " + TextComponent.Translatable("experience.friend.online").GetString() + "</color>";
return false;
}
}
@@ -0,0 +1,58 @@
using System;
using System.Reflection;
using Bd2.Client;
using BD2.GameNames;
using BepInEx.Configuration;
using HarmonyLib;
namespace Bd2BetterExperience.Window;
internal sealed class WindowPreferences : IModule
{
private enum StartupMode { GameDefault, Fullscreen, Windowed }
private static ConfigEntry<StartupMode> mode;
private static MethodInfo fullscreen;
private static MethodInfo windowed;
public string Id => "WindowPreferences";
public string Description => "Choose the startup window mode while respecting launcher instance parameters.";
public void Install(Harmony harmony)
{
mode = Plugin.Settings.Bind("Window", "StartupMode", StartupMode.Fullscreen,
"GameDefault preserves the game's setting. Fullscreen and Windowed apply once at startup. Launcher instance window parameters take priority. Restart the game after changing this setting.");
if (ClientSettings.CurrentInstance != null)
{
Plugin.Log.LogInfo("Startup window mode follows launcher instance parameters");
return;
}
const BindingFlags all = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo initialize = typeof(AppManager).GetGameMethod("InitPCResolution", all, null, Type.EmptyTypes, null)
?? throw new MissingMethodException("AppManager.InitPCResolution");
fullscreen = typeof(AppManager).GetGameMethod(nameof(AppManager.SwitchToFullScreen), all, null, [typeof(bool)], null)
?? throw new MissingMethodException("AppManager.SwitchToFullScreen");
windowed = typeof(AppManager).GetGameMethod(nameof(AppManager.SwitchToWindowScreen), all, null, [typeof(bool)], null)
?? throw new MissingMethodException("AppManager.SwitchToWindowScreen");
harmony.Patch(initialize, postfix: new HarmonyMethod(typeof(WindowPreferences), nameof(AfterResolution)));
}
private static void AfterResolution(AppManager __instance)
{
try
{
switch (mode.Value)
{
case StartupMode.Fullscreen:
fullscreen.Invoke(__instance, [false]);
break;
case StartupMode.Windowed:
windowed.Invoke(__instance, [true]);
break;
}
}
catch (Exception error)
{
Plugin.Log.LogError("Could not apply startup window mode: " + error);
}
}
}
@@ -7,7 +7,7 @@
<RootNamespace>Bd2CaptureEnvironment</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>capture_environment</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="BepInEx">
+1 -1
View File
@@ -7,7 +7,7 @@
<RootNamespace>Bd2CashShop</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>cash_shop</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
+1 -2
View File
@@ -86,7 +86,6 @@ public sealed class Plugin : BaseUnityPlugin
Patch(typeof(GachaProductButtonElement), "Set", nameof(GachaPrice), true, 6);
PatchGeneratedReceiver("<SendLoginPassRequest>b__0", nameof(LoginPassRewards));
PatchGeneratedReceiver("<SendEventRewardRequest>b__0", nameof(EventRewards));
PassRewardPresentation.Install(harmony);
RewardBuffRefresh.Install(harmony);
PrestigeSkinRewardPresentation.Install(harmony, Log);
MethodInfo attendance = typeof(EventPacket).GetGameMethod("RecvAttendanceResponse", All, null,
@@ -455,7 +454,7 @@ public sealed class Plugin : BaseUnityPlugin
foreach (TMP_Text label in container.GetComponentsInChildren<TMP_Text>(true))
{
if (label == price || buy != null && label.transform.IsChildOf(buy.transform) || cancel != null && label.transform.IsChildOf(cancel.transform)) continue;
if (label.text != "购买费用") continue;
if (label.text != LocalTextInfo.GetText(140183)) continue;
RectTransform rect = label.rectTransform;
saved[label] = new PriceLabelState
{
+1 -1
View File
@@ -7,7 +7,7 @@
<RootNamespace>Bd2FBattle</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>fbattle</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="BepInEx"><HintPath>$(BD2BepInExDir)/core/BepInEx.dll</HintPath><Private>false</Private></Reference>
+1 -2
View File
@@ -56,6 +56,5 @@
"fchat.help.target": "Describe the target language in natural language, for example “Simplified Chinese”, “British English” or “Japanese”. Leave this field empty to use your current game UI language. The AI interprets your description when translating.",
"fchat.help.blacklist": "Enter language names or descriptions in natural language, separated by commas, for example “English, Japanese”. Leave empty to allow all languages. The AI must identify the actual language of each message. This cannot be reliably determined locally, so message content may still be sent to your configured AI API even when translation is skipped. Language identification may consume additional tokens and incur charges. Set your API budget accordingly.",
"fchat.error.target_invalid": "Target language must be a single line of at most 200 characters.",
"fchat.error.blacklist_invalid": "Language blacklist must be a single line of at most 2,000 characters.",
"fchat.friend.online": "Online"
"fchat.error.blacklist_invalid": "Language blacklist must be a single line of at most 2,000 characters."
}
+1 -2
View File
@@ -56,6 +56,5 @@
"fchat.help.target": "「簡体字中国語」「イギリス英語」「日本語」など、翻訳先の言語を自然な言葉で指定してください。空欄の場合は現在のゲームの表示言語を使います。AI が入力した説明を解釈して翻訳します。",
"fchat.help.blacklist": "翻訳しない言語の名前や説明を自然な言葉で入力し、複数ある場合は「英語, 日本語」のようにカンマで区切ってください。空欄の場合はすべての言語を許可します。各メッセージの実際の言語を AI が識別する必要があります。端末だけでは確実に判定できないため、翻訳を省略する場合もメッセージが設定した AI API に送信されることがあります。言語の識別で追加のトークンや料金が発生する場合があります。API の予算を適切に設定してください。",
"fchat.error.target_invalid": "翻訳先の言語は 200 文字以内の 1 行で入力してください。",
"fchat.error.blacklist_invalid": "翻訳しない言語は 2000 文字以内の 1 行で入力してください。",
"fchat.friend.online": "オンライン"
"fchat.error.blacklist_invalid": "翻訳しない言語は 2000 文字以内の 1 行で入力してください。"
}
+1 -2
View File
@@ -56,6 +56,5 @@
"fchat.help.target": "“간체 중국어”, “영국 영어”, “일본어”처럼 번역할 대상 언어를 자연어로 입력하세요. 비워 두면 현재 게임 표시 언어를 사용합니다. AI가 입력한 설명을 해석하여 번역합니다.",
"fchat.help.blacklist": "번역하지 않을 언어의 이름이나 설명을 자연어로 입력하세요. 여러 언어는 “영어, 일본어”처럼 쉼표로 구분하세요. 비워 두면 모든 언어를 허용합니다. AI가 각 메시지의 실제 언어를 식별해야 합니다. 기기에서만 이를 정확하게 판단할 수 없으므로 번역을 건너뛰더라도 메시지 내용이 설정한 AI API로 전송될 수 있습니다. 언어 식별에 추가 토큰이 소모되고 요금이 발생할 수 있으니 API 예산을 적절히 설정하세요.",
"fchat.error.target_invalid": "번역 대상 언어는 200자 이내의 한 줄로 입력하세요.",
"fchat.error.blacklist_invalid": "번역 제외 언어는 2000자 이내의 한 줄로 입력하세요.",
"fchat.friend.online": "온라인"
"fchat.error.blacklist_invalid": "번역 제외 언어는 2000자 이내의 한 줄로 입력하세요."
}
+1 -2
View File
@@ -56,6 +56,5 @@
"fchat.help.target": "用自然语言描述希望翻译成的语言,例如“简体中文”“英式英语”或“日语”。留空时使用你当前的游戏界面语言。AI 会根据你的描述理解目标语言并翻译。",
"fchat.help.blacklist": "用自然语言填写不需要翻译的语言名称或描述,多个语言用逗号分隔,例如“英语, 日语”。留空表示不限制语言。AI 需要识别每条消息的实际语言,本地无法可靠判断,因此即使最终跳过翻译,消息内容仍可能发送至你配置的 AI 接口。语言识别可能额外消耗 Token 并产生费用,请合理设置 API 预算。",
"fchat.error.target_invalid": "目标语言需为单行文本,最多 200 个字符。",
"fchat.error.blacklist_invalid": "语言黑名单需为单行文本,最多 2000 个字符。",
"fchat.friend.online": "在线"
"fchat.error.blacklist_invalid": "语言黑名单需为单行文本,最多 2000 个字符。"
}
+1 -2
View File
@@ -56,6 +56,5 @@
"fchat.help.target": "用自然語言描述希望翻譯成的語言,例如「繁體中文」「英式英語」或「日語」。留空時使用你目前的遊戲介面語言。AI 會根據你的描述理解目標語言並翻譯。",
"fchat.help.blacklist": "用自然語言填寫不需要翻譯的語言名稱或描述,多個語言用逗號分隔,例如「英語, 日語」。留空表示不限制語言。AI 需要辨識每則訊息的實際語言,本機無法可靠判斷,因此即使最終跳過翻譯,訊息內容仍可能傳送至你設定的 AI 介面。語言辨識可能額外消耗 Token 並產生費用,請合理設定 API 預算。",
"fchat.error.target_invalid": "目標語言須為單行文字,最多 200 個字元。",
"fchat.error.blacklist_invalid": "語言黑名單須為單行文字,最多 2000 個字元。",
"fchat.friend.online": "線上"
"fchat.error.blacklist_invalid": "語言黑名單須為單行文字,最多 2000 個字元。"
}
+1 -1
View File
@@ -7,7 +7,7 @@
<RootNamespace>Bd2FChat</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>fchat</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
-1
View File
@@ -27,7 +27,6 @@ public sealed class Plugin : BaseUnityPlugin
NativeChatTranslation.Install(harmony);
TranslationSettingsUI.Install(harmony);
ServerTextPolicy.Install(harmony, Logger);
FriendPresence.Install(harmony);
Logger.LogInfo("Client chat translation and server text policy installed");
}
catch (Exception error)
Binary file not shown.
@@ -6,7 +6,7 @@
<EnableNETAnalyzers>false</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
<AssemblyName>ExamplePlugin</AssemblyName>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
<BD2ManagedDir Condition="'$(BD2ManagedDir)' == ''">$(GameDir)/BrownDust II_Data/Managed</BD2ManagedDir>
<!-- GameDir belongs in local Directory.Build.props or on the command line. -->
</PropertyGroup>
+2 -1
View File
@@ -26,7 +26,7 @@ internal sealed class ClientRouting : IDisposable
MethodInfo makeCDNInfo = Game.Method(() => BDNetwork.CommonPacket.MakeCDNInfo(null));
if (load == null || sendMaintenance == null || makeCDNInfo == null)
{
throw new MissingMethodException("2.37.13 server/resource routing methods were not found");
throw new MissingMethodException("2.38.11 server/resource routing methods were not found");
}
harmony.Patch(load, postfix: new HarmonyMethod(typeof(ClientRouting), nameof(ApplyServerOriginHook)));
harmony.Patch(sendMaintenance, prefix: new HarmonyMethod(typeof(ClientRouting), nameof(ApplyServerOriginHook)));
@@ -126,6 +126,7 @@ internal sealed class ClientRouting : IDisposable
resources = RequestResourcePolicy(log, config);
}
ValidatePolicy(effectiveMode, resources);
SoundBankCache.Initialize(resources.bundle_version, log);
return new ClientRouting(log, config, resources, localResourceServer);
}
catch
@@ -1,45 +0,0 @@
using System;
using System.Reflection;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
namespace Bd2LocalIdentity;
internal static class DebuggerErrorNotification
{
internal static void Install(Harmony harmony, ManualLogSource logger)
{
Type notifier = AccessTools.TypeByName("SRDebugger.UI.Other.ErrorNotifier");
MethodInfo show = notifier?.GetMethod(
"ShowErrorWarning", BindingFlags.Instance | BindingFlags.Public,
null, Type.EmptyTypes, null);
MethodInfo awake = notifier?.GetMethod(
"Awake", BindingFlags.Instance | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
if (notifier == null || !typeof(MonoBehaviour).IsAssignableFrom(notifier) ||
show == null || show.ReturnType != typeof(void) ||
awake == null || awake.ReturnType != typeof(void))
{
throw new MissingMethodException("SRDebugger ErrorNotifier methods were not found (client version mismatch)");
}
harmony.Patch(show, prefix: new HarmonyMethod(typeof(DebuggerErrorNotification), nameof(SuppressWarning)));
harmony.Patch(awake, postfix: new HarmonyMethod(typeof(DebuggerErrorNotification), nameof(HideNotifier)));
logger.LogInfo("SRDebugger blinking error notification disabled; console logging remains active");
}
private static bool SuppressWarning(object __instance)
{
HideNotifier(__instance);
return false;
}
private static void HideNotifier(object __instance)
{
if (__instance is Component component && component != null)
{
component.gameObject.SetActive(false);
}
}
}
@@ -26,7 +26,7 @@ internal static class FieldTransitionDiagnostics
internal static void Install(Harmony harmony, ManualLogSource logger)
{
Log = logger;
Patch(harmony, Game.Method(() => QuestPacket.SendQuestClearRequest(0)), nameof(QuestClearSend));
Patch(harmony, Game.Method(() => QuestPacket.SendQuestClearRequest(0, false)), nameof(QuestClearSend));
Patch(harmony, typeof(QuestPacket).GetGameMethod("RecvQuestClearResponse",
BindingFlags.NonPublic | BindingFlags.Static, null, [typeof(byte[]), typeof(int), typeof(int), typeof(Action)], null), nameof(QuestClearReceive));
Patch(harmony, Game.Method(() => QuestInfo.PlayQuestCinemaTimeline(0, false, null, null)), nameof(QuestCinema));
@@ -0,0 +1,114 @@
using System;
using System.Reflection;
using System.Threading;
using BD2.GameNames;
using BDNetwork;
using HarmonyLib;
using Proto.Design.common;
using Proto.Net;
namespace Bd2LocalIdentity;
internal static class InventoryStackPolicy
{
private static int policy;
internal static void Reset() => Volatile.Write(ref policy, 0);
internal static bool Apply(int value)
{
if (value == 0)
{
return false;
}
int next = value == 2 ? 2 : 1;
return Interlocked.Exchange(ref policy, next) != next;
}
internal static int EffectiveLimit(int original) => Volatile.Read(ref policy) == 2 ? int.MaxValue : original;
internal static void Install(Harmony harmony)
{
harmony.Patch(Game.Getter<LifeItemTable, int>(item => item.StackCount),
postfix: new HarmonyMethod(typeof(InventoryStackPolicy), nameof(LifeStackLimit)));
harmony.Patch(Game.Method(() => CommonPacket.GetItemCountOfAddition(default, 0, default)),
prefix: new HarmonyMethod(typeof(InventoryStackPolicy), nameof(RemainingStackRoom)));
harmony.Patch(typeof(InventoryPacket).GetGameMethod("IsEnoughStorageSlot", BindingFlags.Static | BindingFlags.NonPublic),
prefix: new HarmonyMethod(typeof(InventoryStackPolicy), nameof(StorageCapacity)));
harmony.Patch(typeof(InventoryPacket).GetGameMethod("IsEnoughInventorySlot", BindingFlags.Static | BindingFlags.NonPublic),
prefix: new HarmonyMethod(typeof(InventoryStackPolicy), nameof(InventoryCapacity)));
}
private static void LifeStackLimit(ref int __result)
{
if (__result > 0)
{
__result = EffectiveLimit(__result);
}
}
private static bool Stackable(EElementType type) => (int)type is 5 or 8 or 9 or 14;
private static long StackRoom(EElementType type, int id, EItemInvenType inventory, int limit)
{
long room = 0;
foreach (ItemDBInfo item in (inventory == EItemInvenType.Inven
? CommonPacket.GetItemDictionary(type) : CommonPacket.GetKeepItemDictionary(type)).Values)
{
if (item.Id == id)
{
room += Math.Max(0L, (long)limit - item.Count);
if (room >= int.MaxValue)
{
return int.MaxValue;
}
}
}
return room;
}
private static bool RemainingStackRoom(EElementType __0, int __1, EItemInvenType __2, ref int __result)
{
if (!Stackable(__0))
{
return true;
}
ItemBaseDTO item = DataManager.GetItemDTO(__0, __1);
if (item == null || item.StackCount <= 0)
{
return true;
}
__result = (int)StackRoom(__0, __1, __2, EffectiveLimit(item.StackCount));
return false;
}
private static bool StorageCapacity(EElementType __0, int __1, int __2, ref bool __result)
=> Capacity(__0, __1, __2, EItemInvenType.Storeage, ref __result);
private static bool InventoryCapacity(EElementType __0, int __1, int __2, ref bool __result)
=> Capacity(__0, __1, __2, EItemInvenType.Inven, ref __result);
private static bool Capacity(EElementType type, int id, int count, EItemInvenType destination, ref bool result)
{
if (!Stackable(type) || CommonPacket.UserInfo == null)
{
return true;
}
ItemBaseDTO item = DataManager.GetItemDTO(type, id);
if (item == null || item.StackCount <= 0)
{
return true;
}
int limit = EffectiveLimit(item.StackCount);
long remaining = Math.Max(0L, (long)count - StackRoom(type, id, destination, limit));
long needed = remaining / limit + (remaining % limit == 0 ? 0 : 1);
int used = destination == EItemInvenType.Inven ? CommonPacket.InventoryItemList.Count : CommonPacket.AllItemKeepList.Count;
int slots = destination == EItemInvenType.Inven ? CommonPacket.UserInfo.InvenSlot : CommonPacket.UserInfo.StorageSlot;
result = count > 0 && (needed == 0 || used + needed <= slots);
if (!result)
{
UIManager.OpenBarNotice(LocalTextInfo.GetText(destination == EItemInvenType.Inven ? 601 : 600), false, null);
}
return false;
}
}
+44 -10
View File
@@ -19,6 +19,7 @@ namespace Bd2LocalIdentity;
internal static class ItemStackRefresh
{
private const int NotifyField = 1000;
private const int PolicyField = 1001;
private const int RefreshItems = 1 << 0;
private const int RefreshLife = 1 << 1;
private static readonly FieldInfo KeepItems = typeof(CommonPacket).GetGameField("_itemKeepInfoDic", BindingFlags.Static | BindingFlags.NonPublic);
@@ -33,17 +34,39 @@ internal static class ItemStackRefresh
{
throw new MissingFieldException(nameof(CommonPacket), "_itemKeepInfoDic");
}
harmony.Patch(typeof(NetworkManager).GetGameMethod("OnAfterResponse", BindingFlags.Instance | BindingFlags.NonPublic,
null, [typeof(PacketData), typeof(ResponseData)], null),
postfix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(AfterResponse)));
InventoryStackPolicy.Install(harmony);
harmony.Patch(typeof(NetworkManager).GetGameMethod("ResponseCheck", BindingFlags.Instance | BindingFlags.NonPublic,
null, [typeof(string), typeof(PacketData), typeof(ResponseData), typeof(byte[])], null),
prefix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(BeforeResponse)));
harmony.Patch(typeof(CommonPacket).GetGameMethod(nameof(CommonPacket.Reset), BindingFlags.Static | BindingFlags.Public),
prefix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(Reset)));
harmony.Patch(typeof(CommonPacket).GetGameMethod(nameof(CommonPacket.SendLoginUserRequest), BindingFlags.Static | BindingFlags.Public),
prefix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(Reset)));
harmony.Patch(Game.Method<NetworkManager>(network => network.Refresh()),
prefix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(Reset)));
harmony.Patch(Game.Method(() => InventoryPacket.RecvItemStorageInfo(null, 0, 0)),
prefix: new HarmonyMethod(typeof(ItemStackRefresh), nameof(BeforeStorage)));
host.StartCoroutine(Reload());
}
private static void AfterResponse(ResponseData __1)
private static void Reset()
{
int flags = Flags(__1?.notify);
InventoryStackPolicy.Reset();
Interlocked.Exchange(ref pending, 0);
reloadingStorage = false;
}
private static void BeforeResponse(ResponseData __2)
{
if (__2 == null || __2.errorType != 0)
{
return;
}
(int flags, int policy) = ReadNotify(__2.notify);
if (InventoryStackPolicy.Apply(policy))
{
Log.LogInfo("Inventory stack policy applied: unlimited=" + (policy == 2));
}
for (int seen = Volatile.Read(ref pending); flags != 0 && (seen & flags) != flags;)
{
int previous = Interlocked.CompareExchange(ref pending, seen | flags, seen);
@@ -55,29 +78,40 @@ internal static class ItemStackRefresh
}
}
private static int Flags(string notify)
private static (int Flags, int Policy) ReadNotify(string notify)
{
if (string.IsNullOrEmpty(notify))
{
return 0;
return (0, 0);
}
try
{
using var input = new CodedInputStream(Convert.FromBase64String(notify));
int flags = 0;
int policy = 0;
for (uint tag; (tag = input.ReadTag()) != 0;)
{
if (tag == WireFormat.MakeTag(NotifyField, WireFormat.WireType.Varint))
{
return (int)input.ReadUInt64();
flags |= (int)input.ReadUInt64();
}
else if (tag == WireFormat.MakeTag(PolicyField, WireFormat.WireType.Varint))
{
ulong value = input.ReadUInt64();
policy = value == 1 || value == 2 ? (int)value : 1;
}
else
{
input.SkipLastField();
}
input.SkipLastField();
}
return (flags, policy);
}
catch (Exception ex) when (ex is FormatException or InvalidProtocolBufferException)
{
// The game itself reports a malformed notify.
}
return 0;
return (0, 0);
}
// Item storage replies add to the counts the client already holds, so the
+1 -1
View File
@@ -7,7 +7,7 @@
<RootNamespace>Bd2LocalIdentity</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>local_identity</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
-7
View File
@@ -43,7 +43,6 @@ public sealed class Plugin : BaseUnityPlugin
AppDomain.CurrentDomain.ProcessExit += delegate { DisposeRouting(); };
AppDomain.CurrentDomain.DomainUnload += delegate { DisposeRouting(); };
}
Type appManager = typeof(AppManager);
MethodInfo getter = Game.Getter<AppManager, bool>(app => app.IsPlatformLogin);
if (getter == null || getter.ReturnType != typeof(bool) || getter.GetParameters().Length != 0)
{
@@ -57,18 +56,13 @@ public sealed class Plugin : BaseUnityPlugin
harmony.Patch(getter, prefix: new HarmonyMethod(prefix));
TryInstall("OS time zone device country", () => SystemTimeZoneRegion.Install(harmony, Logger));
ClientPresentation.Initialize(Logger);
LocalAccountPolicy.Initialize(Logger);
ClientDiagnostics.Initialize(Logger);
Type introUI = typeof(IntroUI);
Routing.Install(harmony);
TryInstall("startup fullscreen", () => ClientPresentation.InstallStartupFullscreen(harmony, appManager));
TryInstall("performance overlay suppression", () => ClientPresentation.InstallPerformanceOverlaySuppression(harmony));
TryInstall("debugger error notification suppression", () => DebuggerErrorNotification.Install(harmony, Logger));
TryInstall("maintenance timeout guard", () => ClientDiagnostics.InstallMaintenanceTimeoutGuard(harmony, introUI));
TryInstall("age-gate persistence", () => LocalAccountPolicy.InstallAgeGatePersistence(harmony));
TryInstall("database diagnostics", () => ClientDiagnostics.InstallDatabaseDiagnostics(harmony));
TryInstall("commission navigation completion", () => CommissionNavigation.Install(harmony, Logger));
TryInstall("field reward position ordering", () => FieldRewardPosition.Install(harmony, Logger));
TryInstall("battle checkpoint", () => BattleCheckpoint.Install(harmony, Logger));
TryInstall("battle preparation recovery", () => BattlePreparation.Install(harmony));
@@ -81,7 +75,6 @@ public sealed class Plugin : BaseUnityPlugin
TryInstall("notice presentation", () => NoticePresentation.Install(harmony));
TryInstall("event request diagnostics", () => EventRequestDiagnostics.Install(harmony, Logger));
TryInstall("item stack refresh", () => ItemStackRefresh.Install(harmony, this, Logger));
TryInstall("room placement stability", () => RoomPlacementStability.Install(harmony, Logger));
Logger.LogInfo("Local identity active: AppManager.IsPlatformLogin => false");
}
catch (Exception ex)
+80
View File
@@ -0,0 +1,80 @@
using System.Globalization;
using System.IO;
using Bd2.Client;
using BepInEx.Logging;
using UnityEngine;
namespace Bd2LocalIdentity;
internal static class SoundBankCache
{
internal static void Initialize(string bundleVersion, ManualLogSource log)
{
string instanceRoot = ClientSettings.CurrentInstance?.Root;
string persistent = string.IsNullOrEmpty(instanceRoot)
? Application.persistentDataPath
: Path.Combine(instanceRoot, "unity", "persistent");
string soundData = Path.GetFullPath(Path.Combine(persistent, "SoundData"));
string patched = Path.Combine(soundData, "Patched");
string marker = Path.Combine(soundData, "bank-cache.version");
string version = string.Join("\n", Application.version, bundleVersion,
PlayerPrefs.GetInt("SoundQuality", 1).ToString(CultureInfo.InvariantCulture));
ValidateAncestors(soundData);
if (File.Exists(marker))
{
RejectReparsePoint(marker);
if (File.ReadAllText(marker) == version) return;
}
bool cleared = Directory.Exists(patched);
if (cleared)
{
ValidateTree(patched);
DeleteTree(patched);
}
Directory.CreateDirectory(soundData);
File.WriteAllText(marker, version);
if (cleared) log.LogInfo("Cleared extracted sound banks for resource version " + bundleVersion);
}
private static void ValidateAncestors(string path)
{
for (DirectoryInfo directory = new(path); directory != null; directory = directory.Parent)
{
if (directory.Exists) RejectReparsePoint(directory.FullName);
}
}
private static void ValidateTree(string path)
{
RejectReparsePoint(path);
foreach (string entry in Directory.EnumerateFileSystemEntries(path))
{
FileAttributes attributes = RejectReparsePoint(entry);
if ((attributes & FileAttributes.Directory) != 0) ValidateTree(entry);
}
}
private static void DeleteTree(string path)
{
RejectReparsePoint(path);
foreach (string entry in Directory.EnumerateFileSystemEntries(path))
{
FileAttributes attributes = RejectReparsePoint(entry);
if ((attributes & FileAttributes.Directory) != 0)
DeleteTree(entry);
else
File.Delete(entry);
}
Directory.Delete(path);
}
private static FileAttributes RejectReparsePoint(string path)
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReparsePoint) != 0)
throw new InvalidDataException("Sound bank cache must not contain symbolic links or junctions: " + path);
return attributes;
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
<RootNamespace>Bd2LoginUI</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>login_ui</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
<BD2GameVersion>2.38.11</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
-2
View File
@@ -192,8 +192,6 @@ internal static class UpdateCompatibility
bool compatible = true;
foreach (KeyValuePair<string, string> item in required)
{
// CaptureEnvironment is an official-client evidence tool, never a player plugin.
if (item.Key == "capture_environment") continue;
if (!plugins.TryGetValue(item.Key, out string current) || !AtLeast(current, item.Value, null))
{
Log?.LogWarning($"Client update required: plugin={DiagnosticValue(item.Key)}, loaded={DiagnosticValue(current)}, minimum={DiagnosticValue(item.Value)}");
+15
View File
@@ -0,0 +1,15 @@
{
"plugins": [
{"id": "game_names", "project": "GameNames/GameNames.csproj", "framework": "netstandard2.0", "file": "BD2.GameNames.dll", "shared_runtime": true},
{"id": "local_identity", "project": "LocalIdentity/LocalIdentity.csproj", "framework": "netstandard2.1", "file": "BD2LocalIdentity.dll", "version_key": "local_identity", "game_sdk": true, "dependencies": ["game_names"]},
{"id": "login_ui", "project": "LoginUI/LoginUI.csproj", "framework": "netstandard2.1", "file": "BD2LoginUI.dll", "version_key": "login_ui", "game_sdk": true, "dependencies": ["game_names"]},
{"id": "cash_shop", "project": "CashShop/CashShop.csproj", "framework": "netstandard2.1", "file": "BD2CashShop.dll", "version_key": "cash_shop", "game_sdk": true, "dependencies": ["game_names"]},
{"id": "fchat", "project": "FChat/FChat.csproj", "framework": "netstandard2.1", "file": "BD2FChat.dll", "version_key": "fchat", "game_sdk": true, "dependencies": ["game_names", "login_ui"]},
{"id": "fbattle", "project": "FBattle/FBattle.csproj", "framework": "netstandard2.1", "file": "BD2FBattle.dll", "version_key": "fbattle", "game_sdk": true, "dependencies": ["game_names", "local_identity"]},
{"id": "better_experience", "project": "BetterExperience/BetterExperience.csproj", "framework": "netstandard2.1", "file": "BD2BetterExperience.dll", "version_key": "better_experience", "game_sdk": true, "dependencies": ["game_names"]},
{"id": "brown_dust_x_accel", "project": "BrownDustXAccel/BrownDustXAccel.csproj", "framework": "netstandard2.1", "file": "BD2BrownDustXAccel.dll"}
],
"tools": [
{"project": "CaptureEnvironment/CaptureEnvironment.csproj"}
]
}