Compare commits

..

17 Commits

Author SHA1 Message Date
ParantezTech c990b7799f Merge branch 'main' of https://github.com/sharpemu/sharpemu 2026-07-31 01:47:13 +03:00
Berk e7149bf41f Shader cfg ssa (#707)
* [shader] add scalar control flow graph
* [shader] add gen5 branch resolver
* [shader] add scalar reaching definitions
* [shader] add cfg and dataflow tests
* [shader] guard descriptors from unresolved registers
2026-07-31 01:43:28 +03:00
Berk 444af50f4b Shader cfg ssa (#707)
* [shader] add scalar control flow graph

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [shader] add scalar control flow graph

* [shader] add gen5 branch resolver

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [shader] add gen5 branch resolver

* [shader] add scalar reaching definitions

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [shader] add scalar reaching definitions

* [shader] add cfg and dataflow tests

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [shader] add cfg and dataflow tests

* [shader] guard descriptors from unresolved registers

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [shader] guard descriptors from unresolved registers

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 01:39:56 +03:00
Berk 5864328e35 Merge media decoding into one FFmpeg bridge (#706)
* [media] merge bink into shared ffmpeg bridge

* [avplayer] decode in process and fix stream info size

* [font] add glyph and teardown exports

* [build] bump ffmpeg runtime to 3b502d4

* [font] add glyph and teardown exports

* [build] bump ffmpeg runtime to 3b502d4

* [avplayer] decode in process

* [font] add glyph and teardown exports

* [build] bump ffmpeg runtime to 3b502d4
2026-07-31 01:31:14 +03:00
Daniel Freak 753ddf93be [GUI] Update window chrome controls (#700) 2026-07-30 17:03:57 +03:00
Astell 5f1bd5a77c fix vulkan error from astrobot (#689)
* fix vulkan error from astrobot

* a bit of a clean

* a bit of a clean
2026-07-30 12:58:43 +03:00
Daniel Freak f08308daf2 [GUI] Redesign options page (#699) 2026-07-30 12:58:22 +03:00
Daniel Freak 77f22973cb [GUI] Update library page layout (#690)
* [GUI] Add horizontal game tiles

* [GUI] Update launching elements layout

* [GUI] Change cards format to squares
2026-07-30 02:47:15 +03:00
Berk 996de70f52 Game compat updates (#691)
* [agc] Add indirect draws

* [video] Match render target views

* [savedata] Allow dialog reinit

* [ime] Add default profile

* [GUI] update missing translations for profile box
2026-07-29 15:59:57 +03:00
Berk d5108e854d chore: bump version to 0.0.3-hotfix-2 (#687) 2026-07-29 01:50:26 +03:00
ParantezTech b020f1676a Merge branch 'main' of https://github.com/sharpemu/sharpemu 2026-07-29 01:48:28 +03:00
ParantezTech 02938b5d5b [GUI] removed not official Discord link from GUI 2026-07-29 01:47:35 +03:00
Berk 7b7a48a834 [CI] Commits are now automatically added to the release notes (#686) 2026-07-29 01:47:21 +03:00
Daniel Freak faf49f689d [GUI] Add live localization bindings and fill missing locales (#685) 2026-07-29 01:25:48 +03:00
Daniel Freak 882a6c06e0 [GUI] add custom top-bar across al platforms (#682) 2026-07-28 21:24:43 +03:00
ParantezTech b21dd9fb92 [GUI] reworked languages for missing translations and added new ones 2026-07-28 17:38:53 +03:00
Daniel Freak b07e4f2bc6 [GUI] add game library watcher & remove rescan button (#678) 2026-07-28 17:09:22 +03:00
77 changed files with 6893 additions and 1723 deletions
+61 -4
View File
@@ -231,6 +231,11 @@ jobs:
permissions: permissions:
contents: write contents: write
steps: steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download build artifacts - name: Download build artifacts
uses: actions/download-artifact@v8 uses: actions/download-artifact@v8
with: with:
@@ -258,6 +263,61 @@ jobs:
tar -czf "release-assets/sharpemu-${VERSION}-linux-x64.tar.gz" -C "${linux_dir}" . tar -czf "release-assets/sharpemu-${VERSION}-linux-x64.tar.gz" -C "${linux_dir}" .
tar -czf "release-assets/sharpemu-${VERSION}-osx-x64.tar.gz" -C "${macos_dir}" . tar -czf "release-assets/sharpemu-${VERSION}-osx-x64.tar.gz" -C "${macos_dir}" .
- name: Build release notes
shell: bash
env:
MAX_COMMITS: 200
RELEASE_TAG: ${{ needs.init.outputs.release-tag }}
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
SHORT_SHA: ${{ needs.init.outputs.short-sha }}
VERSION: ${{ needs.init.outputs.version }}
run: |
set -euo pipefail
previous_tag="$(git describe --tags --abbrev=0 --match 'v*' "${RELEASE_TAG}^" 2>/dev/null || true)"
if [ -n "${previous_tag}" ]; then
range="${previous_tag}..${RELEASE_TAG}"
else
range="${RELEASE_TAG}"
fi
git log --no-merges --reverse --pretty=tformat:"%H%x1f%h%x1f%s" "${range}" > commits.txt
total="$(wc -l < commits.txt)"
{
printf 'Automated SharpEmu v%s build for commit [`%s`](%s/commit/%s).\n\n' \
"${VERSION}" "${SHORT_SHA}" "${REPO_URL}" "${GITHUB_SHA}"
if [ -n "${previous_tag}" ]; then
printf '## Changes since %s\n\n' "${previous_tag}"
else
printf '## Changes\n\n'
fi
if [ "${total}" -eq 0 ]; then
printf '_No commits since %s._\n' "${previous_tag}"
else
head -n "${MAX_COMMITS}" commits.txt | while IFS=$'\x1f' read -r sha short subject; do
printf -- '- %s ([`%s`](%s/commit/%s))\n' "${subject}" "${short}" "${REPO_URL}" "${sha}"
done
if [ "${total}" -gt "${MAX_COMMITS}" ]; then
printf '\n_…and %s more commits._\n' "$((total - MAX_COMMITS))"
fi
fi
printf '\n'
if [ -n "${previous_tag}" ]; then
printf '**Full changelog**: %s/compare/%s...%s\n' "${REPO_URL}" "${previous_tag}" "${RELEASE_TAG}"
else
printf '**Full changelog**: %s/commits/%s\n' "${REPO_URL}" "${RELEASE_TAG}"
fi
} > release-notes.md
cat release-notes.md
- name: Create release - name: Create release
shell: bash shell: bash
env: env:
@@ -265,7 +325,6 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_NAME: ${{ needs.init.outputs.release-name }} RELEASE_NAME: ${{ needs.init.outputs.release-name }}
RELEASE_TAG: ${{ needs.init.outputs.release-tag }} RELEASE_TAG: ${{ needs.init.outputs.release-tag }}
VERSION: ${{ needs.init.outputs.version }}
run: | run: |
mapfile -t assets < <(find release-assets -maxdepth 1 -type f \( -name '*.zip' -o -name '*.tar.gz' \) | sort) mapfile -t assets < <(find release-assets -maxdepth 1 -type f \( -name '*.zip' -o -name '*.tar.gz' \) | sort)
if [ "${#assets[@]}" -ne 3 ]; then if [ "${#assets[@]}" -ne 3 ]; then
@@ -273,8 +332,6 @@ jobs:
exit 1 exit 1
fi fi
notes="Automated SharpEmu v${VERSION} build for commit ${GITHUB_SHA}."
if gh release view "${RELEASE_TAG}" >/dev/null 2>&1; then if gh release view "${RELEASE_TAG}" >/dev/null 2>&1; then
echo "Release ${RELEASE_TAG} already exists and will not be modified." >&2 echo "Release ${RELEASE_TAG} already exists and will not be modified." >&2
exit 1 exit 1
@@ -283,4 +340,4 @@ jobs:
gh release create "${RELEASE_TAG}" "${assets[@]}" \ gh release create "${RELEASE_TAG}" "${assets[@]}" \
--verify-tag \ --verify-tag \
--title "${RELEASE_NAME}" \ --title "${RELEASE_NAME}" \
--notes "${notes}" --notes-file release-notes.md
+1 -1
View File
@@ -9,7 +9,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<SharpEmuVersion>0.0.3-hotfix-1</SharpEmuVersion> <SharpEmuVersion>0.0.3-hotfix-2</SharpEmuVersion>
<Version>$(SharpEmuVersion)</Version> <Version>$(SharpEmuVersion)</Version>
<RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot> <RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot>
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+6
View File
@@ -19,6 +19,12 @@ precedence = "aggregate"
SPDX-FileCopyrightText = "SharpEmu Emulator Project" SPDX-FileCopyrightText = "SharpEmu Emulator Project"
SPDX-License-Identifier = "GPL-2.0-or-later" SPDX-License-Identifier = "GPL-2.0-or-later"
[[annotations]]
path = "src/SharpEmu.GUI/Assets/Fonts/MaterialSymbolsRounded-*.ttf"
precedence = "aggregate"
SPDX-FileCopyrightText = "2026 Google LLC"
SPDX-License-Identifier = "Apache-2.0"
[[annotations]] [[annotations]]
path = "src/SharpEmu.LibAtrac9/**" path = "src/SharpEmu.LibAtrac9/**"
precedence = "aggregate" precedence = "aggregate"
+58
View File
@@ -157,6 +157,62 @@ def ensure_tag_does_not_exist(
raise ReleaseError(f"Tag {tag} already exists on {remote}.") raise ReleaseError(f"Tag {tag} already exists on {remote}.")
def get_previous_tag(repository_root: Path) -> str:
try:
return run_git(
"describe",
"--tags",
"--abbrev=0",
"--match",
"v*",
"HEAD",
cwd=repository_root,
capture_output=True,
)
except ReleaseError:
return ""
def get_release_commits(
repository_root: Path,
previous_tag: str,
) -> list[str]:
revision_range = f"{previous_tag}..HEAD" if previous_tag else "HEAD"
output = run_git(
"log",
"--no-merges",
"--reverse",
"--pretty=tformat:%h %s",
revision_range,
cwd=repository_root,
capture_output=True,
)
return output.splitlines()
def print_release_notes_preview(repository_root: Path) -> None:
previous_tag = get_previous_tag(repository_root)
commits = get_release_commits(repository_root, previous_tag)
print()
if previous_tag:
print(f"Commits since {previous_tag} ({len(commits)}):")
else:
print(f"Commits in this release ({len(commits)}):")
if not commits:
print(" (none)")
for commit in commits:
print(f" {commit}")
print()
print("These commits go into the generated release notes.")
def read_version(props_path: Path) -> str: def read_version(props_path: Path) -> str:
if not props_path.exists(): if not props_path.exists():
raise ReleaseError(f"Version file not found: {props_path}") raise ReleaseError(f"Version file not found: {props_path}")
@@ -323,6 +379,8 @@ def create_release_tag(
remote, remote,
) )
print_release_notes_preview(repository_root)
run_git( run_git(
"tag", "tag",
"-a", "-a",
+3 -4
View File
@@ -111,15 +111,14 @@ SPDX-License-Identifier: GPL-2.0-or-later
name is a fixed constant, not derived from the RID/architecture: each name is a fixed constant, not derived from the RID/architecture: each
publish output only ever holds one architecture's binaries anyway, so publish output only ever holds one architecture's binaries anyway, so
varying the name added a class of bugs (RID resolution timing, host-OS varying the name added a class of bugs (RID resolution timing, host-OS
vs. target-RID mixups) for no benefit. Runtime code (Program.cs's vs. target-RID mixups) for no benefit. Runtime code (FfmpegRuntime)
FfmpegNativeBinkFrameSource uses the same literal "plugins" folder uses the same literal "plugins" folder name. -->
name. -->
<PropertyGroup> <PropertyGroup>
<NativeLibraryFolderName>plugins</NativeLibraryFolderName> <NativeLibraryFolderName>plugins</NativeLibraryFolderName>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<FfmpegRuntimeTag>2c92585</FfmpegRuntimeTag> <FfmpegRuntimeTag>3b502d4</FfmpegRuntimeTag>
<FfmpegRuntimeDir> <FfmpegRuntimeDir>
$(BaseIntermediateOutputPath)ffmpeg-runtime/$(FfmpegRuntimeTag)/$(RuntimeIdentifier)</FfmpegRuntimeDir> $(BaseIntermediateOutputPath)ffmpeg-runtime/$(FfmpegRuntimeTag)/$(RuntimeIdentifier)</FfmpegRuntimeDir>
<FfmpegRuntimePackage Condition="'$(RuntimeIdentifier)' == 'win-x64'">ffmpeg-windows-x64.zip</FfmpegRuntimePackage> <FfmpegRuntimePackage Condition="'$(RuntimeIdentifier)' == 'win-x64'">ffmpeg-windows-x64.zip</FfmpegRuntimePackage>
+16
View File
@@ -0,0 +1,16 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
/// <summary>
/// Stateless trailing action that opens the library folder picker.
/// </summary>
public sealed class AddFolderTile : LibraryTile
{
public static AddFolderTile Instance { get; } = new();
private AddFolderTile()
{
}
}
+4
View File
@@ -15,6 +15,8 @@ cascade order so individual launcher views do not redefine global visuals.
<ResourceDictionary.MergedDictionaries> <ResourceDictionary.MergedDictionaries>
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Tokens.axaml" /> <ResourceInclude Source="avares://SharpEmu.GUI/Themes/Tokens.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/SettingRow.axaml" /> <ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/SettingRow.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/OptionsControls.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/SplitNumericUpDown.axaml" />
</ResourceDictionary.MergedDictionaries> </ResourceDictionary.MergedDictionaries>
</ResourceDictionary> </ResourceDictionary>
</Application.Resources> </Application.Resources>
@@ -25,8 +27,10 @@ cascade order so individual launcher views do not redefine global visuals.
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Base.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Base.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Surfaces.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Surfaces.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Buttons.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Buttons.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Chrome.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Inputs.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Inputs.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Console.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Console.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Library.axaml" /> <StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Library.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Options.axaml" />
</Application.Styles> </Application.Styles>
</Application> </Application>
+1
View File
@@ -18,6 +18,7 @@ public partial class App : Application
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{ {
desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;
desktop.MainWindow = new MainWindow(); desktop.MainWindow = new MainWindow();
} }
@@ -0,0 +1,11 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using Avalonia.Controls;
namespace SharpEmu.GUI.Controls.Settings;
/// <summary>
/// Numeric input whose native spinner is presented as a separate split button
/// </summary>
public sealed class SplitNumericUpDown : NumericUpDown;
+125 -13
View File
@@ -8,7 +8,16 @@ using Avalonia.Media.Imaging;
namespace SharpEmu.GUI; namespace SharpEmu.GUI;
public sealed class GameEntry : INotifyPropertyChanged [Flags]
internal enum GameEntryChanges
{
None = 0,
Metadata = 1,
Cover = 2,
Background = 4,
}
public sealed class GameEntry : LibraryTile, INotifyPropertyChanged
{ {
// Placeholder gradients for games without cover art, picked // Placeholder gradients for games without cover art, picked
// deterministically from the game name so a game keeps its color. // deterministically from the game name so a game keeps its color.
@@ -27,29 +36,39 @@ public sealed class GameEntry : INotifyPropertyChanged
private Bitmap? _cover; private Bitmap? _cover;
private IBrush? _placeholderBrush; private IBrush? _placeholderBrush;
private long _sizeBytes; private long _sizeBytes;
private string _name;
private string? _titleId;
private string? _version;
private string? _coverPath;
private string? _backgroundPath;
private string _initials;
private FileStamp _coverStamp;
private FileStamp _backgroundStamp;
public GameEntry( public GameEntry(
string name, string? titleId, string? version, string path, long sizeBytes, string name, string? titleId, string? version, string path, long sizeBytes,
string? coverPath, string? backgroundPath) string? coverPath, string? backgroundPath)
{ {
Name = name; _name = name;
TitleId = titleId; _titleId = titleId;
Version = version; _version = version;
Path = path; Path = path;
_sizeBytes = sizeBytes; _sizeBytes = sizeBytes;
CoverPath = coverPath; _coverPath = coverPath;
BackgroundPath = backgroundPath; _backgroundPath = backgroundPath;
Initials = ComputeInitials(name); _initials = ComputeInitials(name);
_coverStamp = FileStamp.Read(coverPath);
_backgroundStamp = FileStamp.Read(backgroundPath);
} }
public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangedEventHandler? PropertyChanged;
public string Name { get; } public string Name => _name;
public string? TitleId { get; } public string? TitleId => _titleId;
/// <summary>Content version from sce_sys/param.json, e.g. "01.000.000".</summary> /// <summary>Content version from sce_sys/param.json, e.g. "01.000.000".</summary>
public string? Version { get; } public string? Version => _version;
public string Path { get; } public string Path { get; }
@@ -75,10 +94,10 @@ public sealed class GameEntry : INotifyPropertyChanged
} }
/// <summary>Path to the cover art image shipped with the game, if found.</summary> /// <summary>Path to the cover art image shipped with the game, if found.</summary>
public string? CoverPath { get; } public string? CoverPath => _coverPath;
/// <summary>Path to the key art (pic0/pic1) shipped with the game, if found.</summary> /// <summary>Path to the key art (pic0/pic1) shipped with the game, if found.</summary>
public string? BackgroundPath { get; } public string? BackgroundPath => _backgroundPath;
/// <summary> /// <summary>
/// Decoded key art used as the window backdrop while this game is /// Decoded key art used as the window backdrop while this game is
@@ -86,7 +105,7 @@ public sealed class GameEntry : INotifyPropertyChanged
/// </summary> /// </summary>
public Bitmap? Background { get; set; } public Bitmap? Background { get; set; }
public string Initials { get; } public string Initials => _initials;
// Built lazily: brushes are AvaloniaObjects that must be created on the // Built lazily: brushes are AvaloniaObjects that must be created on the
// UI thread, while GameEntry itself is constructed on the scan thread. // UI thread, while GameEntry itself is constructed on the scan thread.
@@ -121,6 +140,74 @@ public sealed class GameEntry : INotifyPropertyChanged
/// <summary>Formatted install size badge shown in the launch bar.</summary> /// <summary>Formatted install size badge shown in the launch bar.</summary>
public string SizeText => FormatSize(SizeBytes); public string SizeText => FormatSize(SizeBytes);
/// <summary>
/// Applies a fresh filesystem scan to this presentation object so its
/// ListBox container and selection remain stable
/// </summary>
internal GameEntryChanges UpdateFrom(GameEntry scanned)
{
if (!Path.Equals(scanned.Path, GameLibraryPath.Comparison))
{
throw new ArgumentException("Only matching game paths can be reconciled", nameof(scanned));
}
var changes = GameEntryChanges.None;
if (!string.Equals(_name, scanned.Name, StringComparison.Ordinal))
{
_name = scanned.Name;
_initials = ComputeInitials(scanned.Name);
_placeholderBrush = null;
RaisePropertyChanged(nameof(Name));
RaisePropertyChanged(nameof(Initials));
RaisePropertyChanged(nameof(PlaceholderBrush));
changes |= GameEntryChanges.Metadata;
}
if (!string.Equals(_titleId, scanned.TitleId, StringComparison.Ordinal))
{
_titleId = scanned.TitleId;
RaisePropertyChanged(nameof(TitleId));
RaisePropertyChanged(nameof(HasTitleId));
changes |= GameEntryChanges.Metadata;
}
if (!string.Equals(_version, scanned.Version, StringComparison.Ordinal))
{
_version = scanned.Version;
RaisePropertyChanged(nameof(Version));
RaisePropertyChanged(nameof(VersionText));
RaisePropertyChanged(nameof(HasVersion));
changes |= GameEntryChanges.Metadata;
}
if (!string.Equals(_coverPath, scanned.CoverPath, StringComparison.Ordinal)
|| _coverStamp != scanned._coverStamp)
{
_coverPath = scanned.CoverPath;
_coverStamp = scanned._coverStamp;
var previousCover = Cover;
Cover = null;
previousCover?.Dispose();
changes |= GameEntryChanges.Cover;
}
if (!string.Equals(_backgroundPath, scanned.BackgroundPath, StringComparison.Ordinal)
|| _backgroundStamp != scanned._backgroundStamp)
{
_backgroundPath = scanned.BackgroundPath;
_backgroundStamp = scanned._backgroundStamp;
var previousBackground = Background;
Background = null;
previousBackground?.Dispose();
changes |= GameEntryChanges.Background;
}
return changes;
}
private void RaisePropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private static string ComputeInitials(string name) private static string ComputeInitials(string name)
{ {
var initials = name var initials = name
@@ -164,4 +251,29 @@ public sealed class GameEntry : INotifyPropertyChanged
_ => $"{bytes} B", _ => $"{bytes} B",
}; };
} }
private readonly record struct FileStamp(long Length, long LastWriteTimeUtcTicks)
{
public static FileStamp Read(string? path)
{
if (path is null)
{
return default;
}
try
{
var file = new FileInfo(path);
return file.Exists
? new FileStamp(file.Length, file.LastWriteTimeUtc.Ticks)
: default;
}
catch (Exception exception) when (
exception is IOException
or UnauthorizedAccessException)
{
return default;
}
}
}
} }
+17
View File
@@ -0,0 +1,17 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
internal static class GameLibraryPath
{
public static StringComparer Comparer { get; } =
OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal;
public static StringComparison Comparison { get; } =
OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
}
+98
View File
@@ -0,0 +1,98 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
internal sealed record GameLibraryReconciliation(
IReadOnlyList<GameEntry> Games,
IReadOnlyList<GameEntry> CoversToLoad,
IReadOnlySet<GameEntry> BackgroundsChanged);
/// <summary>
/// Applies filesystem scan results while preserving presentation object
/// identity for games that remain in the library
/// </summary>
internal static class GameLibraryReconciler
{
public static GameLibraryReconciliation Reconcile(
IReadOnlyList<GameEntry> current,
IReadOnlyList<GameEntry> scanned)
{
var existingByPath = current.ToDictionary(game => game.Path, GameLibraryPath.Comparer);
var merged = new List<GameEntry>(scanned.Count);
var coversToLoad = new List<GameEntry>();
var backgroundsChanged = new HashSet<GameEntry>();
foreach (var scannedGame in scanned)
{
if (!existingByPath.TryGetValue(scannedGame.Path, out var existing))
{
merged.Add(scannedGame);
if (scannedGame.CoverPath is not null)
{
coversToLoad.Add(scannedGame);
}
continue;
}
var changes = existing.UpdateFrom(scannedGame);
merged.Add(existing);
if ((changes & GameEntryChanges.Cover) != 0 && existing.CoverPath is not null)
{
coversToLoad.Add(existing);
}
if ((changes & GameEntryChanges.Background) != 0)
{
backgroundsChanged.Add(existing);
}
}
return new GameLibraryReconciliation(merged, coversToLoad, backgroundsChanged);
}
/// <summary>
/// Reorders, inserts and removes only the items needed to reach the desired
/// visible sequence
/// </summary>
public static void ReconcileVisibleGames(
IList<GameEntry> visible,
IReadOnlyList<GameEntry> desired)
{
for (var index = 0; index < desired.Count; index++)
{
var game = desired[index];
if (index < visible.Count && ReferenceEquals(visible[index], game))
{
continue;
}
var existingIndex = -1;
for (var candidate = index + 1; candidate < visible.Count; candidate++)
{
if (ReferenceEquals(visible[candidate], game))
{
existingIndex = candidate;
break;
}
}
if (existingIndex >= 0)
{
var existing = visible[existingIndex];
visible.RemoveAt(existingIndex);
visible.Insert(index, existing);
}
else
{
visible.Insert(index, game);
}
}
while (visible.Count > desired.Count)
{
visible.RemoveAt(visible.Count - 1);
}
}
}
+147
View File
@@ -0,0 +1,147 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
/// <summary>
/// Watches configured game folders and collapses filesystem bursts into one
/// library refresh request
/// </summary>
internal sealed class GameLibraryWatcher : IDisposable
{
private static readonly TimeSpan DefaultDebounceInterval = TimeSpan.FromMilliseconds(600);
private readonly object _sync = new();
private readonly TimeSpan _debounceInterval;
private readonly List<FileSystemWatcher> _watchers = [];
private Timer? _debounceTimer;
private bool _disposed;
internal GameLibraryWatcher(TimeSpan? debounceInterval = null)
{
_debounceInterval = debounceInterval ?? DefaultDebounceInterval;
}
public event EventHandler? RefreshRequested;
/// <summary>
/// Replaces the watched roots with the current configured game folders
/// </summary>
public void Watch(IReadOnlyList<string> folders)
{
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
foreach (var watcher in _watchers)
{
watcher.Dispose();
}
_watchers.Clear();
_debounceTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
foreach (var folder in folders.Distinct(GameLibraryPath.Comparer))
{
if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder))
{
continue;
}
try
{
var watcher = new FileSystemWatcher(folder)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName
| NotifyFilters.DirectoryName
| NotifyFilters.LastWrite
| NotifyFilters.Size,
};
watcher.Created += OnFileSystemChanged;
watcher.Changed += OnFileSystemChanged;
watcher.Deleted += OnFileSystemChanged;
watcher.Renamed += OnFileSystemChanged;
watcher.Error += OnWatcherError;
watcher.EnableRaisingEvents = true;
_watchers.Add(watcher);
}
catch (Exception exception) when (
exception is ArgumentException
or IOException
or UnauthorizedAccessException)
{
Console.Error.WriteLine(
$"[GUI][WARN] Could not watch game folder '{folder}': {exception.Message}");
}
}
}
}
private void OnFileSystemChanged(object sender, FileSystemEventArgs args)
=> ScheduleRefresh();
private void OnWatcherError(object sender, ErrorEventArgs args)
{
Console.Error.WriteLine(
$"[GUI][WARN] Game library watcher reported an error: {args.GetException().Message}");
ScheduleRefresh();
}
private void ScheduleRefresh()
{
lock (_sync)
{
if (_disposed)
{
return;
}
if (_debounceTimer is null)
{
_debounceTimer = new Timer(
static state => ((GameLibraryWatcher)state!).RaiseRefreshRequested(),
this,
_debounceInterval,
Timeout.InfiniteTimeSpan);
}
else
{
_debounceTimer.Change(_debounceInterval, Timeout.InfiniteTimeSpan);
}
}
}
private void RaiseRefreshRequested()
{
lock (_sync)
{
if (_disposed)
{
return;
}
}
RefreshRequested?.Invoke(this, EventArgs.Empty);
}
public void Dispose()
{
lock (_sync)
{
if (_disposed)
{
return;
}
_disposed = true;
_debounceTimer?.Dispose();
_debounceTimer = null;
foreach (var watcher in _watchers)
{
watcher.Dispose();
}
_watchers.Clear();
}
}
}
+21
View File
@@ -45,6 +45,9 @@ public sealed class GuiSettings
/// <summary>UI language, matching a file code under Languages/ (e.g. "en", "tr").</summary> /// <summary>UI language, matching a file code under Languages/ (e.g. "en", "tr").</summary>
public string Language { get; set; } = "en"; public string Language { get; set; } = "en";
/// <summary>Default text-entry profile exposed to games.</summary>
public string DefaultProfile { get; set; } = "Sharp";
/// <summary>Publish launcher/game status to Discord Rich Presence.</summary> /// <summary>Publish launcher/game status to Discord Rich Presence.</summary>
public bool DiscordRichPresence { get; set; } = true; public bool DiscordRichPresence { get; set; } = true;
@@ -112,6 +115,18 @@ public sealed class GuiSettings
settings.EnvironmentToggles = FilterNullOrEmpty(settings.EnvironmentToggles); settings.EnvironmentToggles = FilterNullOrEmpty(settings.EnvironmentToggles);
settings.LogLevel ??= "Info"; settings.LogLevel ??= "Info";
settings.Language ??= "en"; settings.Language ??= "en";
var legacyProfile = settings.EnvironmentToggles
.Select(entry => entry.Split('=', 2, StringSplitOptions.TrimEntries))
.FirstOrDefault(parts =>
parts.Length == 2 &&
string.Equals(parts[0], "SHARPEMU_DEFAULT_PROFILE", StringComparison.OrdinalIgnoreCase));
settings.EnvironmentToggles.RemoveAll(entry =>
string.Equals(
entry.Split('=', 2, StringSplitOptions.TrimEntries)[0],
"SHARPEMU_DEFAULT_PROFILE",
StringComparison.OrdinalIgnoreCase));
settings.DefaultProfile = NormalizeDefaultProfile(
legacyProfile is { Length: 2 } ? legacyProfile[1] : settings.DefaultProfile);
settings.DiscordClientId ??= "1525606762248540221"; settings.DiscordClientId ??= "1525606762248540221";
if (settings.RenderResolutionScale <= 0 || settings.RenderResolutionScale > 2.0) if (settings.RenderResolutionScale <= 0 || settings.RenderResolutionScale > 2.0)
{ {
@@ -152,6 +167,12 @@ public sealed class GuiSettings
return $"{width}x{height}"; return $"{width}x{height}";
} }
internal static string NormalizeDefaultProfile(string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrEmpty(trimmed) ? "Sharp" : trimmed;
}
public void Save() public void Save()
{ {
try try
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} لعبة", "Page.GameCount.Other": "{0} لعبة",
"Library.SearchWatermark": "ابحث في المكتبة...", "Library.SearchWatermark": "ابحث في المكتبة...",
"Library.AddFolder": " إضافة مجلد", "Library.AddFolder": "إضافة مجلد",
"Library.Rescan": "⟳ إعادة الفحص",
"Library.OpenFile": "فتح ملف...", "Library.OpenFile": "فتح ملف...",
"Library.Context.Launch": "تشغيل", "Library.Context.Launch": "تشغيل",
@@ -67,6 +66,8 @@
"Options.Language.Label": "لغة المحاكي", "Options.Language.Label": "لغة المحاكي",
"Options.Language.Desc": "اللغة المستخدمة في جميع أنحاء المشغل. تُطبق فوراً.", "Options.Language.Desc": "اللغة المستخدمة في جميع أنحاء المشغل. تُطبق فوراً.",
"Options.DefaultProfile.Label": "اسم الملف الشخصي الافتراضي",
"Options.DefaultProfile.Desc": "الاسم المستخدم عندما تطلب لعبة إدخال نص. القيمة الافتراضية هي Sharp.",
"Common.On": "تشغيل", "Common.On": "تشغيل",
"Common.Off": "إيقاف", "Common.Off": "إيقاف",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "تسجيل تخصيصات الذاكرة المباشرة وإخفاقاتها في وحدة التحكم.\nاستخدمه عندما تنهار لعبة أو تُغلق أثناء الإقلاع.", "Options.Env.LogDirectMemory.Desc": "تسجيل تخصيصات الذاكرة المباشرة وإخفاقاتها في وحدة التحكم.\nاستخدمه عندما تنهار لعبة أو تُغلق أثناء الإقلاع.",
"Options.Env.LogIo.Desc": "تسجيل فتح الملفات وقراءتها وحلّ المسارات في وحدة التحكم.\nاستخدمه عندما لا تجد لعبة ملفات بياناتها أثناء الإقلاع.", "Options.Env.LogIo.Desc": "تسجيل فتح الملفات وقراءتها وحلّ المسارات في وحدة التحكم.\nاستخدمه عندما لا تجد لعبة ملفات بياناتها أثناء الإقلاع.",
"Options.Env.LogNp.Desc": "تسجيل نداءات مكتبة NP (شبكة PlayStation) في وحدة التحكم.", "Options.Env.LogNp.Desc": "تسجيل نداءات مكتبة NP (شبكة PlayStation) في وحدة التحكم.",
"Options.Env.GuestImageCpuSync.Desc": "إعادة رفع أسطح الضيف التي تعيد كتابتها شيفرة المعالج الخاصة باللعبة.\nاتركه مغلقًا عادة. شغّله للألعاب التي لا تصل أسطحها المرسومة بالمعالج إلى الشاشة.\nيكلّف أداءً ويسبب مشاكل في بعض الألعاب مثل GTA V.",
"Common.Save": "حفظ", "Common.Save": "حفظ",
"Common.Cancel": "إلغاء", "Common.Cancel": "إلغاء",
"PerGame.Title": "إعدادات خاصة باللعبة — {0} ({1})", "PerGame.Title": "إعدادات خاصة باللعبة — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "دسكورد", "About.Discord.Label": "دسكورد",
"About.Discord.Desc": "انضم إلى المجتمع واحصل على الدعم وتابع التطوير.", "About.Discord.Desc": "انضم إلى المجتمع واحصل على الدعم وتابع التطوير.",
"About.GithubButton": "ساهم على GitHub!", "About.GithubButton": "ساهم على GitHub!",
"About.DiscordButton": "انضم إلى دسكوردنا!", "About.DiscordComingSoon": "قريبًا",
"Updater.Auto.Label": "التحقق من التحديثات عند بدء التشغيل", "Updater.Auto.Label": "التحقق من التحديثات عند بدء التشغيل",
"Updater.Auto.Desc": "يتحقق من GitHub دون تأخير بدء التشغيل.", "Updater.Auto.Desc": "يتحقق من GitHub دون تأخير بدء التشغيل.",
"Updater.Label": "التحديثات", "Updater.Label": "التحديثات",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "انتهت مهلة التحقق من التحديثات بعد 10 ثوانٍ.", "Updater.Status.Timeout": "انتهت مهلة التحقق من التحديثات بعد 10 ثوانٍ.",
"Updater.Status.Failed": "تعذر التحقق من التحديثات.", "Updater.Status.Failed": "تعذر التحقق من التحديثات.",
"Updater.Status.ChecksumFailed": "فشل التحديث المنزَّل في اجتياز تحقق SHA-256.", "Updater.Status.ChecksumFailed": "فشل التحديث المنزَّل في اجتياز تحقق SHA-256.",
"Updater.Status.Unsupported": "يتطلب التحديث التلقائي إصدار x64 لنظام Windows أو Linux أو macOS." "Updater.Status.Unsupported": "يتطلب التحديث التلقائي إصدار x64 لنظام Windows أو Linux أو macOS.",
"Options.Graphics": "الرسومات",
"Options.Section.Rendering": "التصيير",
"Options.Section.Display": "العرض",
"Options.RenderResolution.Label": "الدقة الداخلية",
"Options.RenderResolution.Desc": "تصيير الأهداف خارج الشاشة بدقة أقل من الدقة الأصلية ثم رفع دقتها عند العرض. تمنح القيم الأقل مساحة أكبر لوحدة معالجة الرسوميات مقابل جودة الصورة؛ يُطبق عند التشغيل التالي.",
"Options.RenderResolution.Native": "100% (أصلية)",
"Options.WindowMode.Label": "وضع النافذة",
"Options.WindowMode.Desc": "نافذة عادية، أو سطح مكتب بلا حدود، أو ملء شاشة حصري.",
"Options.WindowMode.Windowed": "نافذة",
"Options.WindowMode.Borderless": "بلا حدود",
"Options.WindowMode.Exclusive": "حصري",
"Options.Resolution.Label": "الدقة",
"Options.Resolution.Desc": "حجم النافذة الأولي أو دقة ملء الشاشة الحصرية.",
"Options.Display.Label": "الشاشة",
"Options.Display.Desc": "الشاشة المستخدمة للتوسيط وملء الشاشة.",
"Options.RefreshRate.Label": "معدل التحديث",
"Options.RefreshRate.Desc": "معدل تحديث ملء الشاشة الحصري. يختار الوضع التلقائي أقرب نمط.",
"Options.RefreshRate.Automatic": "تلقائي",
"Options.Scaling.Label": "التحجيم",
"Options.Scaling.Desc": "تحجيم صورة النظام الضيف الأصلية دون تغيير دقتها الداخلية.",
"Options.Scaling.Fit": "ملاءمة",
"Options.Scaling.Cover": "تغطية",
"Options.Scaling.Stretch": "تمديد",
"Options.Scaling.Integer": "عدد صحيح",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "استخدام عرض FIFO لإخراج خالٍ من تمزق الصورة.",
"Options.Hdr.Label": "إخراج HDR",
"Options.Hdr.Desc": "استخدام HDR عندما تدعمه الشاشة المحددة وواجهة الرسومات. يعود الوضع التلقائي إلى SDR.",
"Options.Hdr.Auto": "تلقائي"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} jogos", "Page.GameCount.Other": "{0} jogos",
"Library.SearchWatermark": "Pesquisar na biblioteca…", "Library.SearchWatermark": "Pesquisar na biblioteca…",
"Library.AddFolder": " Adicionar pasta", "Library.AddFolder": "Adicionar pasta",
"Library.Rescan": "⟳ Atualizar biblioteca",
"Library.OpenFile": "Abrir arquivo…", "Library.OpenFile": "Abrir arquivo…",
"Library.Context.Launch": "Jogar", "Library.Context.Launch": "Jogar",
@@ -35,6 +34,7 @@
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e suas traduções SPIR-V para a pasta shader-dumps.\nUse ao reportar bugs de shader ou renderização.", "Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e suas traduções SPIR-V para a pasta shader-dumps.\nUse ao reportar bugs de shader ou renderização.",
"Options.Env.LogDirectMemory.Desc": "Registra alocações de memória direta e falhas no console.\nUse quando um jogo aborta ou fecha durante a inicialização (boot).", "Options.Env.LogDirectMemory.Desc": "Registra alocações de memória direta e falhas no console.\nUse quando um jogo aborta ou fecha durante a inicialização (boot).",
"Options.Env.LogNp.Desc": "Registra chamadas da biblioteca NP (PlayStation Network) no console.", "Options.Env.LogNp.Desc": "Registra chamadas da biblioteca NP (PlayStation Network) no console.",
"Options.Env.GuestImageCpuSync.Desc": "Recarrega as superfícies do convidado que o próprio código de CPU do jogo reescreve.\nDeixe desativado normalmente. Ative para títulos cujas superfícies desenhadas pela CPU nunca chegam à tela.\nCusta desempenho e causa regressões em alguns títulos, como GTA V.",
"Options.Section.Emulation": "EMULAÇÃO", "Options.Section.Emulation": "EMULAÇÃO",
"Options.Section.Logging": "LOGS", "Options.Section.Logging": "LOGS",
"Options.Section.Launcher": "INICIALIZADOR", "Options.Section.Launcher": "INICIALIZADOR",
@@ -76,6 +76,8 @@
"Options.Language.Label": "Idioma do emulador", "Options.Language.Label": "Idioma do emulador",
"Options.Language.Desc": "Idioma usado em toda a interface do emulador. A alteração é aplicada imediatamente.", "Options.Language.Desc": "Idioma usado em toda a interface do emulador. A alteração é aplicada imediatamente.",
"Options.DefaultProfile.Label": "Nome de perfil padrão",
"Options.DefaultProfile.Desc": "Nome usado quando um jogo solicita entrada de texto. O padrão é Sharp.",
"Common.On": "Ativado", "Common.On": "Ativado",
"Common.Off": "Desativado", "Common.Off": "Desativado",
@@ -142,7 +144,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Participe da comunidade, obtenha suporte e acompanhe o desenvolvimento.", "About.Discord.Desc": "Participe da comunidade, obtenha suporte e acompanhe o desenvolvimento.",
"About.GithubButton": "Contribua no GitHub!", "About.GithubButton": "Contribua no GitHub!",
"About.DiscordButton": "Entre no nosso Discord!", "About.DiscordComingSoon": "Em breve",
"Library.Context.GameSettings": "Configurações do jogo…", "Library.Context.GameSettings": "Configurações do jogo…",
"Options.Env.WritableApp0.Desc": "Permite que os jogos criem e gravem arquivos dentro da própria pasta de instalação.\nNecessário para dumps não empacotados que gravam seus saves ou configurações em /app0.", "Options.Env.WritableApp0.Desc": "Permite que os jogos criem e gravem arquivos dentro da própria pasta de instalação.\nNecessário para dumps não empacotados que gravam seus saves ou configurações em /app0.",
@@ -169,5 +171,34 @@
"Updater.Status.Timeout": "A verificação de atualizações expirou após 10 segundos.", "Updater.Status.Timeout": "A verificação de atualizações expirou após 10 segundos.",
"Updater.Status.Failed": "Não foi possível verificar as atualizações.", "Updater.Status.Failed": "Não foi possível verificar as atualizações.",
"Updater.Status.ChecksumFailed": "A atualização baixada falhou na verificação SHA-256.", "Updater.Status.ChecksumFailed": "A atualização baixada falhou na verificação SHA-256.",
"Updater.Status.Unsupported": "A atualização automática requer um build x64 para Windows, Linux ou macOS." "Updater.Status.Unsupported": "A atualização automática requer um build x64 para Windows, Linux ou macOS.",
"Options.Graphics": "Gráficos",
"Options.Section.Rendering": "RENDERIZAÇÃO",
"Options.Section.Display": "TELA",
"Options.RenderResolution.Label": "Resolução interna",
"Options.RenderResolution.Desc": "Renderiza alvos fora da tela abaixo da resolução nativa e amplia na apresentação. Valores menores trocam qualidade de imagem por folga da GPU; entra em vigor na próxima inicialização.",
"Options.RenderResolution.Native": "100% (nativa)",
"Options.WindowMode.Label": "Modo de janela",
"Options.WindowMode.Desc": "Janela normal, área de trabalho sem bordas ou tela cheia exclusiva.",
"Options.WindowMode.Windowed": "Em janela",
"Options.WindowMode.Borderless": "Sem bordas",
"Options.WindowMode.Exclusive": "Exclusiva",
"Options.Resolution.Label": "Resolução",
"Options.Resolution.Desc": "Tamanho inicial da janela ou resolução de tela cheia exclusiva.",
"Options.Display.Label": "Tela",
"Options.Display.Desc": "Monitor usado para centralização e tela cheia.",
"Options.RefreshRate.Label": "Taxa de atualização",
"Options.RefreshRate.Desc": "Taxa de atualização da tela cheia exclusiva. O modo automático seleciona o modo mais próximo.",
"Options.RefreshRate.Automatic": "Automática",
"Options.Scaling.Label": "Escala",
"Options.Scaling.Desc": "Dimensiona a imagem nativa do sistema convidado sem alterar sua resolução interna.",
"Options.Scaling.Fit": "Ajustar",
"Options.Scaling.Cover": "Preencher",
"Options.Scaling.Stretch": "Esticar",
"Options.Scaling.Integer": "Inteira",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Usa apresentação FIFO para evitar cortes na imagem.",
"Options.Hdr.Label": "Saída HDR",
"Options.Hdr.Desc": "Usa HDR quando a tela selecionada e o backend gráfico oferecem suporte. O modo automático retorna ao SDR.",
"Options.Hdr.Auto": "Automático"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} Spiele", "Page.GameCount.Other": "{0} Spiele",
"Library.SearchWatermark": "Bibliothek durchsuchen…", "Library.SearchWatermark": "Bibliothek durchsuchen…",
"Library.AddFolder": " Spielordner hinzufügen", "Library.AddFolder": "Spielordner hinzufügen",
"Library.Rescan": "⟳ Neu scannen",
"Library.OpenFile": "Datei öffnen…", "Library.OpenFile": "Datei öffnen…",
"Library.Context.Launch": "Starten", "Library.Context.Launch": "Starten",
@@ -67,6 +66,8 @@
"Options.Language.Label": "Emulator-Sprache", "Options.Language.Label": "Emulator-Sprache",
"Options.Language.Desc": "Sprache der Benutzeroberfläche. Wird sofort angewendet.", "Options.Language.Desc": "Sprache der Benutzeroberfläche. Wird sofort angewendet.",
"Options.DefaultProfile.Label": "Standardprofilname",
"Options.DefaultProfile.Desc": "Name für Texteingaben in Spielen. Der Standardwert ist Sharp.",
"Common.On": "An", "Common.On": "An",
"Common.Off": "Aus", "Common.Off": "Aus",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "Direkte Speicherzuweisungen und Fehler in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start abbricht oder sich beendet.", "Options.Env.LogDirectMemory.Desc": "Direkte Speicherzuweisungen und Fehler in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start abbricht oder sich beendet.",
"Options.Env.LogIo.Desc": "Datei-Öffnen, -Lesen und Pfadauflösung in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start seine Datendateien nicht findet.", "Options.Env.LogIo.Desc": "Datei-Öffnen, -Lesen und Pfadauflösung in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start seine Datendateien nicht findet.",
"Options.Env.LogNp.Desc": "NP-Bibliotheksaufrufe (PlayStation Network) in der Konsole protokollieren.", "Options.Env.LogNp.Desc": "NP-Bibliotheksaufrufe (PlayStation Network) in der Konsole protokollieren.",
"Options.Env.GuestImageCpuSync.Desc": "Gast-Oberflächen neu hochladen, die der eigene CPU-Code des Spiels überschreibt.\nNormalerweise aus lassen. Für Titel aktivieren, deren CPU-gezeichnete Oberflächen nie auf dem Bildschirm erscheinen.\nKostet Leistung und verursacht bei einigen Titeln wie GTA V Regressionen.",
"Common.Save": "Speichern", "Common.Save": "Speichern",
"Common.Cancel": "Abbrechen", "Common.Cancel": "Abbrechen",
"PerGame.Title": "Spielspezifische Einstellungen — {0} ({1})", "PerGame.Title": "Spielspezifische Einstellungen — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Tritt der Community bei, erhalte Support und verfolge die Entwicklung.", "About.Discord.Desc": "Tritt der Community bei, erhalte Support und verfolge die Entwicklung.",
"About.GithubButton": "Auf GitHub mitwirken!", "About.GithubButton": "Auf GitHub mitwirken!",
"About.DiscordButton": "Tritt unserem Discord bei!", "About.DiscordComingSoon": "Demnächst verfügbar",
"Updater.Auto.Label": "Beim Start nach Updates suchen", "Updater.Auto.Label": "Beim Start nach Updates suchen",
"Updater.Auto.Desc": "Fragt GitHub ab, ohne den Start zu verzögern.", "Updater.Auto.Desc": "Fragt GitHub ab, ohne den Start zu verzögern.",
"Updater.Label": "Updates", "Updater.Label": "Updates",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "Die Updateprüfung ist nach 10 Sekunden abgelaufen.", "Updater.Status.Timeout": "Die Updateprüfung ist nach 10 Sekunden abgelaufen.",
"Updater.Status.Failed": "Updates konnten nicht geprüft werden.", "Updater.Status.Failed": "Updates konnten nicht geprüft werden.",
"Updater.Status.ChecksumFailed": "Das heruntergeladene Update hat die SHA-256-Prüfung nicht bestanden.", "Updater.Status.ChecksumFailed": "Das heruntergeladene Update hat die SHA-256-Prüfung nicht bestanden.",
"Updater.Status.Unsupported": "Automatische Updates erfordern einen x64-Build für Windows, Linux oder macOS." "Updater.Status.Unsupported": "Automatische Updates erfordern einen x64-Build für Windows, Linux oder macOS.",
"Options.Graphics": "Grafik",
"Options.Section.Rendering": "DARSTELLUNG",
"Options.Section.Display": "ANZEIGE",
"Options.RenderResolution.Label": "Interne Auflösung",
"Options.RenderResolution.Desc": "Offscreen-Ziele unterhalb der nativen Auflösung rendern und bei der Ausgabe hochskalieren. Niedrigere Werte tauschen Bildqualität gegen GPU-Reserven; wird beim nächsten Start wirksam.",
"Options.RenderResolution.Native": "100 % (nativ)",
"Options.WindowMode.Label": "Fenstermodus",
"Options.WindowMode.Desc": "Normales Fenster, randloser Desktop oder exklusiver Vollbildmodus.",
"Options.WindowMode.Windowed": "Fenster",
"Options.WindowMode.Borderless": "Randlos",
"Options.WindowMode.Exclusive": "Exklusiv",
"Options.Resolution.Label": "Auflösung",
"Options.Resolution.Desc": "Anfängliche Fenstergröße oder exklusive Vollbildauflösung.",
"Options.Display.Label": "Anzeige",
"Options.Display.Desc": "Monitor für Zentrierung und Vollbilddarstellung.",
"Options.RefreshRate.Label": "Bildwiederholrate",
"Options.RefreshRate.Desc": "Bildwiederholrate im exklusiven Vollbildmodus. Automatisch wählt den nächstgelegenen Modus.",
"Options.RefreshRate.Automatic": "Automatisch",
"Options.Scaling.Label": "Skalierung",
"Options.Scaling.Desc": "Das native Gastbild skalieren, ohne seine interne Auflösung zu ändern.",
"Options.Scaling.Fit": "Einpassen",
"Options.Scaling.Cover": "Ausfüllen",
"Options.Scaling.Stretch": "Strecken",
"Options.Scaling.Integer": "Ganzzahlig",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "FIFO-Präsentation für eine Ausgabe ohne Tearing verwenden.",
"Options.Hdr.Label": "HDR-Ausgabe",
"Options.Hdr.Desc": "HDR verwenden, wenn die ausgewählte Anzeige und das Grafik-Backend es unterstützen. Automatisch fällt auf SDR zurück.",
"Options.Hdr.Auto": "Automatisch"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} spil", "Page.GameCount.Other": "{0} spil",
"Library.SearchWatermark": "Søg i biblioteket…", "Library.SearchWatermark": "Søg i biblioteket…",
"Library.AddFolder": " Tilføj mappe", "Library.AddFolder": "Tilføj mappe",
"Library.Rescan": "⟳ Genindlæs",
"Library.OpenFile": "Åbn fil…", "Library.OpenFile": "Åbn fil…",
"Library.Context.Launch": "Start", "Library.Context.Launch": "Start",
@@ -67,6 +66,8 @@
"Options.Language.Label": "Emulatorsprog", "Options.Language.Label": "Emulatorsprog",
"Options.Language.Desc": "Sprog der bruges i hele launcheren. Anvendes med det samme.", "Options.Language.Desc": "Sprog der bruges i hele launcheren. Anvendes med det samme.",
"Options.DefaultProfile.Label": "Standardprofilnavn",
"Options.DefaultProfile.Desc": "Navn der bruges, når et spil beder om tekstinput. Standardværdien er Sharp.",
"Common.On": "Til", "Common.On": "Til",
"Common.Off": "Fra", "Common.Off": "Fra",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "Log direkte hukommelsestildelinger og fejl til konsollen.\nBrug dette, når et spil afbryder eller lukker under opstart.", "Options.Env.LogDirectMemory.Desc": "Log direkte hukommelsestildelinger og fejl til konsollen.\nBrug dette, når et spil afbryder eller lukker under opstart.",
"Options.Env.LogIo.Desc": "Log åbning og læsning af filer samt stiopslag til konsollen.\nBrug dette, når et spil ikke kan finde sine datafiler under opstart.", "Options.Env.LogIo.Desc": "Log åbning og læsning af filer samt stiopslag til konsollen.\nBrug dette, når et spil ikke kan finde sine datafiler under opstart.",
"Options.Env.LogNp.Desc": "Log NP-bibliotekskald (PlayStation Network) til konsollen.", "Options.Env.LogNp.Desc": "Log NP-bibliotekskald (PlayStation Network) til konsollen.",
"Options.Env.GuestImageCpuSync.Desc": "Genindlæs gæsteoverflader, som spillets egen CPU-kode omskriver.\nLad den være slået fra normalt. Slå til for titler, hvis CPU-tegnede overflader aldrig når skærmen.\nKoster ydeevne og giver regressioner i nogle titler, såsom GTA V.",
"Common.Save": "Gem", "Common.Save": "Gem",
"Common.Cancel": "Annuller", "Common.Cancel": "Annuller",
"PerGame.Title": "Indstillinger pr. spil — {0} ({1})", "PerGame.Title": "Indstillinger pr. spil — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Bliv en del af fællesskabet, få hjælp og følg udviklingen.", "About.Discord.Desc": "Bliv en del af fællesskabet, få hjælp og følg udviklingen.",
"About.GithubButton": "Bidrag på GitHub!", "About.GithubButton": "Bidrag på GitHub!",
"About.DiscordButton": "Bliv medlem af vores Discord!", "About.DiscordComingSoon": "Kommer snart",
"Updater.Auto.Label": "Søg efter opdateringer ved start", "Updater.Auto.Label": "Søg efter opdateringer ved start",
"Updater.Auto.Desc": "Tjekker GitHub uden at forsinke opstarten.", "Updater.Auto.Desc": "Tjekker GitHub uden at forsinke opstarten.",
"Updater.Label": "Opdateringer", "Updater.Label": "Opdateringer",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "Opdateringstjekket fik timeout efter 10 sekunder.", "Updater.Status.Timeout": "Opdateringstjekket fik timeout efter 10 sekunder.",
"Updater.Status.Failed": "Kunne ikke søge efter opdateringer.", "Updater.Status.Failed": "Kunne ikke søge efter opdateringer.",
"Updater.Status.ChecksumFailed": "Den downloadede opdatering bestod ikke SHA-256-verifikationen.", "Updater.Status.ChecksumFailed": "Den downloadede opdatering bestod ikke SHA-256-verifikationen.",
"Updater.Status.Unsupported": "Automatisk opdatering kræver et x64-build til Windows, Linux eller macOS." "Updater.Status.Unsupported": "Automatisk opdatering kræver et x64-build til Windows, Linux eller macOS.",
"Options.Graphics": "Grafik",
"Options.Section.Rendering": "GENGIVELSE",
"Options.Section.Display": "SKÆRM",
"Options.RenderResolution.Label": "Intern opløsning",
"Options.RenderResolution.Desc": "Render offscreen-mål under den oprindelige opløsning, og opskaler dem ved visning. Lavere værdier bytter billedkvalitet for GPU-kapacitet; træder i kraft ved næste start.",
"Options.RenderResolution.Native": "100 % (oprindelig)",
"Options.WindowMode.Label": "Vinduestilstand",
"Options.WindowMode.Desc": "Normalt vindue, kantløst skrivebord eller eksklusiv fuldskærm.",
"Options.WindowMode.Windowed": "Vindue",
"Options.WindowMode.Borderless": "Kantløs",
"Options.WindowMode.Exclusive": "Eksklusiv",
"Options.Resolution.Label": "Opløsning",
"Options.Resolution.Desc": "Oprindelig vinduesstørrelse eller opløsning i eksklusiv fuldskærm.",
"Options.Display.Label": "Skærm",
"Options.Display.Desc": "Skærm, der bruges til centrering og fuldskærm.",
"Options.RefreshRate.Label": "Opdateringshastighed",
"Options.RefreshRate.Desc": "Opdateringshastighed i eksklusiv fuldskærm. Automatisk vælger den nærmeste tilstand.",
"Options.RefreshRate.Automatic": "Automatisk",
"Options.Scaling.Label": "Skalering",
"Options.Scaling.Desc": "Skaler det oprindelige gæstebillede uden at ændre dets interne opløsning.",
"Options.Scaling.Fit": "Tilpas",
"Options.Scaling.Cover": "Udfyld",
"Options.Scaling.Stretch": "Stræk",
"Options.Scaling.Integer": "Heltal",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Brug FIFO-præsentation for output uden tearing.",
"Options.Hdr.Label": "HDR-output",
"Options.Hdr.Desc": "Brug HDR, når den valgte skærm og grafik-backend understøtter det. Automatisk falder tilbage til SDR.",
"Options.Hdr.Auto": "Automatisk"
} }
+17 -3
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} games", "Page.GameCount.Other": "{0} games",
"Library.SearchWatermark": "Search library…", "Library.SearchWatermark": "Search library…",
"Library.AddFolder": " Add folder", "Library.AddFolder": "Add folder",
"Library.Rescan": "⟳ Rescan",
"Library.OpenFile": "Open file…", "Library.OpenFile": "Open file…",
"Library.Context.Launch": "Launch", "Library.Context.Launch": "Launch",
@@ -38,14 +37,24 @@
"Options.Env.LogDirectMemory.Desc": "Log direct memory allocations and failures to the console.\nUse when a game aborts or exits during boot.", "Options.Env.LogDirectMemory.Desc": "Log direct memory allocations and failures to the console.\nUse when a game aborts or exits during boot.",
"Options.Env.LogIo.Desc": "Log file open, read, and path-resolve activity to the console.\nUse when a game cannot find its data files during boot.", "Options.Env.LogIo.Desc": "Log file open, read, and path-resolve activity to the console.\nUse when a game cannot find its data files during boot.",
"Options.Env.LogNp.Desc": "Log NP (PlayStation Network) library calls to the console.", "Options.Env.LogNp.Desc": "Log NP (PlayStation Network) library calls to the console.",
"Options.Env.GuestImageCpuSync.Desc": "Re-upload guest surfaces the game's own CPU code rewrites.\nLeave off normally. Turn on for titles whose CPU-drawn surfaces never reach the screen.\nCosts performance and regresses some titles, such as GTA V.",
"Options.DefaultProfile.Label": "Default profile name",
"Options.DefaultProfile.Desc": "Name used when a game asks for text input. Defaults to Sharp.",
"Options.Section.Emulation": "EMULATION", "Options.Section.Emulation": "EMULATION",
"Options.Section.Logging": "LOGGING", "Options.Section.Logging": "LOGGING",
"Options.Section.Launcher": "LAUNCHER", "Options.Section.Launcher": "LAUNCHER",
"Options.Section.Rendering": "RENDERING",
"Options.Section.Display": "DISPLAY", "Options.Section.Display": "DISPLAY",
"Options.Graphics": "Graphics", "Options.Graphics": "Graphics",
"Options.RenderResolution.Label": "Internal resolution",
"Options.RenderResolution.Desc": "Render offscreen targets below native resolution and upscale on present. Lower values trade image quality for GPU headroom; takes effect on next launch.",
"Options.RenderResolution.Native": "100% (native)",
"Options.WindowMode.Label": "Window mode", "Options.WindowMode.Label": "Window mode",
"Options.WindowMode.Desc": "Regular window, desktop borderless, or exclusive fullscreen.", "Options.WindowMode.Desc": "Regular window, desktop borderless, or exclusive fullscreen.",
"Options.WindowMode.Windowed": "Windowed",
"Options.WindowMode.Borderless": "Borderless",
"Options.WindowMode.Exclusive": "Exclusive",
"Options.Resolution.Label": "Resolution", "Options.Resolution.Label": "Resolution",
"Options.Resolution.Desc": "Initial window size or exclusive fullscreen resolution.", "Options.Resolution.Desc": "Initial window size or exclusive fullscreen resolution.",
"Options.Display.Label": "Display", "Options.Display.Label": "Display",
@@ -55,10 +64,15 @@
"Options.RefreshRate.Automatic": "Automatic", "Options.RefreshRate.Automatic": "Automatic",
"Options.Scaling.Label": "Scaling", "Options.Scaling.Label": "Scaling",
"Options.Scaling.Desc": "Scale the native guest image without changing its internal resolution.", "Options.Scaling.Desc": "Scale the native guest image without changing its internal resolution.",
"Options.Scaling.Fit": "Fit",
"Options.Scaling.Cover": "Cover",
"Options.Scaling.Stretch": "Stretch",
"Options.Scaling.Integer": "Integer",
"Options.VSync.Label": "VSync", "Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Use FIFO presentation for tear-free output.", "Options.VSync.Desc": "Use FIFO presentation for tear-free output.",
"Options.Hdr.Label": "HDR output", "Options.Hdr.Label": "HDR output",
"Options.Hdr.Desc": "Use HDR when the selected display and graphics backend support it. Auto falls back to SDR.", "Options.Hdr.Desc": "Use HDR when the selected display and graphics backend support it. Auto falls back to SDR.",
"Options.Hdr.Auto": "Auto",
"Options.CpuEngine.Label": "CPU engine", "Options.CpuEngine.Label": "CPU engine",
"Options.CpuEngine.Desc": "Execution engine used to run game code.", "Options.CpuEngine.Desc": "Execution engine used to run game code.",
@@ -174,7 +188,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Join the community, get support and follow development.", "About.Discord.Desc": "Join the community, get support and follow development.",
"About.GithubButton": "Contribute in GitHub!", "About.GithubButton": "Contribute in GitHub!",
"About.DiscordButton": "Join our Discord!", "About.DiscordComingSoon": "Coming soon",
"Updater.Auto.Label": "Check for updates on startup", "Updater.Auto.Label": "Check for updates on startup",
"Updater.Auto.Desc": "Checks GitHub without delaying startup.", "Updater.Auto.Desc": "Checks GitHub without delaying startup.",
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} juegos", "Page.GameCount.Other": "{0} juegos",
"Library.SearchWatermark": "Buscar en la biblioteca…", "Library.SearchWatermark": "Buscar en la biblioteca…",
"Library.AddFolder": " Añadir carpeta", "Library.AddFolder": "Añadir carpeta",
"Library.Rescan": "⟳ Volver a escanear",
"Library.OpenFile": "Abrir archivo…", "Library.OpenFile": "Abrir archivo…",
"Library.Context.Launch": "Iniciar", "Library.Context.Launch": "Iniciar",
@@ -67,6 +66,8 @@
"Options.Language.Label": "Idioma del emulador", "Options.Language.Label": "Idioma del emulador",
"Options.Language.Desc": "Idioma utilizado en todo el launcher. Se aplica inmediatamente.", "Options.Language.Desc": "Idioma utilizado en todo el launcher. Se aplica inmediatamente.",
"Options.DefaultProfile.Label": "Nombre de perfil predeterminado",
"Options.DefaultProfile.Desc": "Nombre utilizado cuando un juego solicita introducir texto. El valor predeterminado es Sharp.",
"Common.On": "Encendido", "Common.On": "Encendido",
"Common.Off": "Apagado", "Common.Off": "Apagado",
@@ -135,7 +136,7 @@
"About.Github.LatestCommitDescription": "Último commit en la rama main", "About.Github.LatestCommitDescription": "Último commit en la rama main",
"About.Discord.Desc": "Únete a la comunidad, recibe soporte y sigue el desarrollo.", "About.Discord.Desc": "Únete a la comunidad, recibe soporte y sigue el desarrollo.",
"About.GithubButton": "Contribuye en GitHub!", "About.GithubButton": "Contribuye en GitHub!",
"About.DiscordButton": "Únete a nuestro Discord!", "About.DiscordComingSoon": "Próximamente",
"Library.Context.GameSettings": "Ajustes del juego…", "Library.Context.GameSettings": "Ajustes del juego…",
"Options.Env.Tab": "Entorno", "Options.Env.Tab": "Entorno",
@@ -149,6 +150,7 @@
"Options.Env.LogDirectMemory.Desc": "Registrar en la consola las asignaciones de memoria directa y sus fallos.\nÚsalo cuando un juego se aborte o se cierre durante el arranque.", "Options.Env.LogDirectMemory.Desc": "Registrar en la consola las asignaciones de memoria directa y sus fallos.\nÚsalo cuando un juego se aborte o se cierre durante el arranque.",
"Options.Env.LogIo.Desc": "Registrar en la consola la apertura y lectura de archivos y la resolución de rutas.\nÚsalo cuando un juego no encuentre sus archivos de datos durante el arranque.", "Options.Env.LogIo.Desc": "Registrar en la consola la apertura y lectura de archivos y la resolución de rutas.\nÚsalo cuando un juego no encuentre sus archivos de datos durante el arranque.",
"Options.Env.LogNp.Desc": "Registrar en la consola las llamadas a la biblioteca NP (PlayStation Network).", "Options.Env.LogNp.Desc": "Registrar en la consola las llamadas a la biblioteca NP (PlayStation Network).",
"Options.Env.GuestImageCpuSync.Desc": "Volver a subir las superficies del invitado que reescribe el propio código de CPU del juego.\nDejar desactivado normalmente. Activar en títulos cuyas superficies dibujadas por CPU nunca llegan a la pantalla.\nCuesta rendimiento y causa regresiones en algunos títulos, como GTA V.",
"Common.Save": "Guardar", "Common.Save": "Guardar",
"Common.Cancel": "Cancelar", "Common.Cancel": "Cancelar",
"PerGame.Title": "Ajustes por juego — {0} ({1})", "PerGame.Title": "Ajustes por juego — {0} ({1})",
@@ -169,5 +171,34 @@
"Updater.Status.Timeout": "La comprobación de actualizaciones caducó tras 10 segundos.", "Updater.Status.Timeout": "La comprobación de actualizaciones caducó tras 10 segundos.",
"Updater.Status.Failed": "No se pudieron comprobar las actualizaciones.", "Updater.Status.Failed": "No se pudieron comprobar las actualizaciones.",
"Updater.Status.ChecksumFailed": "La actualización descargada no superó la verificación SHA-256.", "Updater.Status.ChecksumFailed": "La actualización descargada no superó la verificación SHA-256.",
"Updater.Status.Unsupported": "La actualización automática requiere un build x64 de Windows, Linux o macOS." "Updater.Status.Unsupported": "La actualización automática requiere un build x64 de Windows, Linux o macOS.",
"Options.Graphics": "Gráficos",
"Options.Section.Rendering": "RENDERIZADO",
"Options.Section.Display": "PANTALLA",
"Options.RenderResolution.Label": "Resolución interna",
"Options.RenderResolution.Desc": "Renderiza objetivos fuera de pantalla por debajo de la resolución nativa y los reescala al presentar. Los valores inferiores sacrifican calidad de imagen para liberar carga de la GPU; se aplica en el próximo inicio.",
"Options.RenderResolution.Native": "100 % (nativa)",
"Options.WindowMode.Label": "Modo de ventana",
"Options.WindowMode.Desc": "Ventana normal, escritorio sin bordes o pantalla completa exclusiva.",
"Options.WindowMode.Windowed": "En ventana",
"Options.WindowMode.Borderless": "Sin bordes",
"Options.WindowMode.Exclusive": "Exclusiva",
"Options.Resolution.Label": "Resolución",
"Options.Resolution.Desc": "Tamaño inicial de la ventana o resolución de pantalla completa exclusiva.",
"Options.Display.Label": "Pantalla",
"Options.Display.Desc": "Monitor utilizado para centrar y mostrar a pantalla completa.",
"Options.RefreshRate.Label": "Frecuencia de actualización",
"Options.RefreshRate.Desc": "Frecuencia de actualización de la pantalla completa exclusiva. El modo automático selecciona el modo más cercano.",
"Options.RefreshRate.Automatic": "Automática",
"Options.Scaling.Label": "Escalado",
"Options.Scaling.Desc": "Escala la imagen nativa del sistema invitado sin cambiar su resolución interna.",
"Options.Scaling.Fit": "Ajustar",
"Options.Scaling.Cover": "Cubrir",
"Options.Scaling.Stretch": "Estirar",
"Options.Scaling.Integer": "Entero",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Usa presentación FIFO para evitar el desgarro de imagen.",
"Options.Hdr.Label": "Salida HDR",
"Options.Hdr.Desc": "Usa HDR cuando la pantalla seleccionada y el backend gráfico sean compatibles. El modo automático vuelve a SDR.",
"Options.Hdr.Auto": "Automático"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} jeux", "Page.GameCount.Other": "{0} jeux",
"Library.SearchWatermark": "Rechercher dans la bibliothèque…", "Library.SearchWatermark": "Rechercher dans la bibliothèque…",
"Library.AddFolder": " Ajouter un dossier", "Library.AddFolder": "Ajouter un dossier",
"Library.Rescan": "⟳ Analyser à nouveau",
"Library.OpenFile": "Ouvrir un fichier…", "Library.OpenFile": "Ouvrir un fichier…",
"Library.Context.Launch": "Lancer", "Library.Context.Launch": "Lancer",
@@ -35,6 +34,7 @@
"Options.Env.DumpSpirv.Desc": "Exporter les shaders AGC et leurs traductions SPIR-V dans le dossier shader-dumps.\nÀ utiliser pour signaler des bugs de shader ou de rendu.", "Options.Env.DumpSpirv.Desc": "Exporter les shaders AGC et leurs traductions SPIR-V dans le dossier shader-dumps.\nÀ utiliser pour signaler des bugs de shader ou de rendu.",
"Options.Env.LogDirectMemory.Desc": "Journaliser les allocations de mémoire directe et les échecs dans la console.\nÀ utiliser quand un jeu plante ou se ferme pendant le démarrage.", "Options.Env.LogDirectMemory.Desc": "Journaliser les allocations de mémoire directe et les échecs dans la console.\nÀ utiliser quand un jeu plante ou se ferme pendant le démarrage.",
"Options.Env.LogNp.Desc": "Journaliser les appels de la bibliothèque NP (PlayStation Network) dans la console.", "Options.Env.LogNp.Desc": "Journaliser les appels de la bibliothèque NP (PlayStation Network) dans la console.",
"Options.Env.GuestImageCpuSync.Desc": "Recharger les surfaces invité que le code CPU du jeu réécrit lui-même.\nLaisser désactivé normalement. Activer pour les titres dont les surfaces dessinées par le CPU n'atteignent jamais l'écran.\nCoûte des performances et provoque des régressions sur certains titres, comme GTA V.",
"Options.Section.Emulation": "ÉMULATION", "Options.Section.Emulation": "ÉMULATION",
"Options.Section.Logging": "JOURNALISATION", "Options.Section.Logging": "JOURNALISATION",
"Options.Section.Launcher": "LANCEUR", "Options.Section.Launcher": "LANCEUR",
@@ -76,6 +76,8 @@
"Options.Language.Label": "Langue de l’émulateur", "Options.Language.Label": "Langue de l’émulateur",
"Options.Language.Desc": "Langue utilisée dans lensemble du lanceur. Le changement est immédiat.", "Options.Language.Desc": "Langue utilisée dans lensemble du lanceur. Le changement est immédiat.",
"Options.DefaultProfile.Label": "Nom de profil par défaut",
"Options.DefaultProfile.Desc": "Nom utilisé lorsquun jeu demande une saisie de texte. La valeur par défaut est Sharp.",
"Common.On": "Activé", "Common.On": "Activé",
"Common.Off": "Désactivé", "Common.Off": "Désactivé",
@@ -142,7 +144,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Rejoignez la communauté, obtenez de laide et suivez le développement.", "About.Discord.Desc": "Rejoignez la communauté, obtenez de laide et suivez le développement.",
"About.GithubButton": "Contribuer sur GitHub !", "About.GithubButton": "Contribuer sur GitHub !",
"About.DiscordButton": "Rejoindre notre Discord !", "About.DiscordComingSoon": "Bientôt disponible",
"Library.Context.GameSettings": "Paramètres du jeu…", "Library.Context.GameSettings": "Paramètres du jeu…",
"Options.Env.WritableApp0.Desc": "Autoriser les jeux à créer et écrire des fichiers dans leur dossier dinstallation.\nNécessaire pour les dumps non empaquetés qui écrivent leurs sauvegardes ou leur configuration sous /app0.", "Options.Env.WritableApp0.Desc": "Autoriser les jeux à créer et écrire des fichiers dans leur dossier dinstallation.\nNécessaire pour les dumps non empaquetés qui écrivent leurs sauvegardes ou leur configuration sous /app0.",
@@ -169,5 +171,34 @@
"Updater.Status.Timeout": "La vérification des mises à jour a expiré après 10 secondes.", "Updater.Status.Timeout": "La vérification des mises à jour a expiré après 10 secondes.",
"Updater.Status.Failed": "Impossible de vérifier les mises à jour.", "Updater.Status.Failed": "Impossible de vérifier les mises à jour.",
"Updater.Status.ChecksumFailed": "La mise à jour téléchargée a échoué à la vérification SHA-256.", "Updater.Status.ChecksumFailed": "La mise à jour téléchargée a échoué à la vérification SHA-256.",
"Updater.Status.Unsupported": "La mise à jour automatique nécessite un build x64 pour Windows, Linux ou macOS." "Updater.Status.Unsupported": "La mise à jour automatique nécessite un build x64 pour Windows, Linux ou macOS.",
"Options.Graphics": "Graphismes",
"Options.Section.Rendering": "RENDU",
"Options.Section.Display": "AFFICHAGE",
"Options.RenderResolution.Label": "Résolution interne",
"Options.RenderResolution.Desc": "Effectuer le rendu des cibles hors écran sous la résolution native et les mettre à l’échelle lors de laffichage. Les valeurs inférieures réduisent la qualité dimage pour libérer des ressources GPU ; prend effet au prochain lancement.",
"Options.RenderResolution.Native": "100 % (native)",
"Options.WindowMode.Label": "Mode fenêtre",
"Options.WindowMode.Desc": "Fenêtre standard, bureau sans bordures ou plein écran exclusif.",
"Options.WindowMode.Windowed": "Fenêtré",
"Options.WindowMode.Borderless": "Sans bordures",
"Options.WindowMode.Exclusive": "Exclusif",
"Options.Resolution.Label": "Résolution",
"Options.Resolution.Desc": "Taille initiale de la fenêtre ou résolution du plein écran exclusif.",
"Options.Display.Label": "Écran",
"Options.Display.Desc": "Moniteur utilisé pour le centrage et le plein écran.",
"Options.RefreshRate.Label": "Fréquence de rafraîchissement",
"Options.RefreshRate.Desc": "Fréquence de rafraîchissement du plein écran exclusif. Le mode automatique sélectionne le mode le plus proche.",
"Options.RefreshRate.Automatic": "Automatique",
"Options.Scaling.Label": "Mise à l’échelle",
"Options.Scaling.Desc": "Mettre à l’échelle limage native du système invité sans modifier sa résolution interne.",
"Options.Scaling.Fit": "Ajuster",
"Options.Scaling.Cover": "Remplir",
"Options.Scaling.Stretch": "Étirer",
"Options.Scaling.Integer": "Entier",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Utiliser la présentation FIFO pour un affichage sans déchirement.",
"Options.Hdr.Label": "Sortie HDR",
"Options.Hdr.Desc": "Utiliser le HDR lorsque l’écran sélectionné et le backend graphique le prennent en charge. Le mode automatique revient au SDR.",
"Options.Hdr.Auto": "Automatique"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} játékok", "Page.GameCount.Other": "{0} játékok",
"Library.SearchWatermark": "Keresés a könyvtárban", "Library.SearchWatermark": "Keresés a könyvtárban",
"Library.AddFolder": " Mappa hozzáadása", "Library.AddFolder": "Mappa hozzáadása",
"Library.Rescan": "⟳ Újrakeresés",
"Library.OpenFile": "Fájl megnyitása…", "Library.OpenFile": "Fájl megnyitása…",
"Library.Context.Launch": "Inditás", "Library.Context.Launch": "Inditás",
@@ -35,6 +34,7 @@
"Options.Env.DumpSpirv.Desc": "Az AGC-shaderek és azok SPIR-V-fordításainak mentése a shader-dumps mappába.\nHasználd shader- vagy renderelési hibák jelentésekor.", "Options.Env.DumpSpirv.Desc": "Az AGC-shaderek és azok SPIR-V-fordításainak mentése a shader-dumps mappába.\nHasználd shader- vagy renderelési hibák jelentésekor.",
"Options.Env.LogDirectMemory.Desc": "A közvetlen memóriaallokációk és hibák naplózása a konzolra.\nHasználd, ha egy játék a rendszerindítás során megszakad vagy kilép.", "Options.Env.LogDirectMemory.Desc": "A közvetlen memóriaallokációk és hibák naplózása a konzolra.\nHasználd, ha egy játék a rendszerindítás során megszakad vagy kilép.",
"Options.Env.LogNp.Desc": "Az NP (PlayStation Network) könyvtárhívásokat naplózza a konzolra.", "Options.Env.LogNp.Desc": "Az NP (PlayStation Network) könyvtárhívásokat naplózza a konzolra.",
"Options.Env.GuestImageCpuSync.Desc": "Újratölti azokat a vendégfelületeket, amelyeket a játék saját CPU-kódja ír felül.\nNormál esetben hagyd kikapcsolva. Kapcsold be azoknál a címeknél, amelyek CPU-val rajzolt felületei sosem jutnak ki a képernyőre.\nTeljesítménybe kerül, és egyes címeknél, például a GTA V-nél regressziót okoz.",
"Options.Section.Emulation": "EMULÁCIÓ", "Options.Section.Emulation": "EMULÁCIÓ",
"Options.Section.Logging": "LOGOLÁS", "Options.Section.Logging": "LOGOLÁS",
"Options.Section.Launcher": "INDITÓ", "Options.Section.Launcher": "INDITÓ",
@@ -76,6 +76,8 @@
"Options.Language.Label": "Emulátor nyelve", "Options.Language.Label": "Emulátor nyelve",
"Options.Language.Desc": "Az indítóban használt nyelv. Azonnal érvénybe lép.", "Options.Language.Desc": "Az indítóban használt nyelv. Azonnal érvénybe lép.",
"Options.DefaultProfile.Label": "Alapértelmezett profilnév",
"Options.DefaultProfile.Desc": "A játékok szövegbeviteli kéréseinél használt név. Az alapértelmezett érték Sharp.",
"Common.On": "Be", "Common.On": "Be",
"Common.Off": "Ki", "Common.Off": "Ki",
@@ -142,7 +144,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Csatlakozz a közösséghe, kérj segítéget és kövesd nyomon a fejlesztést.", "About.Discord.Desc": "Csatlakozz a közösséghe, kérj segítéget és kövesd nyomon a fejlesztést.",
"About.GithubButton": "Járulj hozzá GitHubon!", "About.GithubButton": "Járulj hozzá GitHubon!",
"About.DiscordButton": "Csatlakozz a Discordunhoz!", "About.DiscordComingSoon": "Hamarosan",
"Library.Context.GameSettings": "Játékbeállítások…", "Library.Context.GameSettings": "Játékbeállítások…",
"Options.Env.WritableApp0.Desc": "Engedélyezi, hogy a játékok fájlokat hozzanak létre és írjanak a telepítési mappájukban.\nA kicsomagolt dumpokhoz szükséges, amelyek a mentéseiket vagy beállításaikat az /app0 alá írják.", "Options.Env.WritableApp0.Desc": "Engedélyezi, hogy a játékok fájlokat hozzanak létre és írjanak a telepítési mappájukban.\nA kicsomagolt dumpokhoz szükséges, amelyek a mentéseiket vagy beállításaikat az /app0 alá írják.",
@@ -169,5 +171,34 @@
"Updater.Status.Timeout": "A frissítés-ellenőrzés 10 másodperc után túllépte az időkorlátot.", "Updater.Status.Timeout": "A frissítés-ellenőrzés 10 másodperc után túllépte az időkorlátot.",
"Updater.Status.Failed": "Nem sikerült frissítéseket keresni.", "Updater.Status.Failed": "Nem sikerült frissítéseket keresni.",
"Updater.Status.ChecksumFailed": "A letöltött frissítés nem ment át az SHA-256-ellenőrzésen.", "Updater.Status.ChecksumFailed": "A letöltött frissítés nem ment át az SHA-256-ellenőrzésen.",
"Updater.Status.Unsupported": "Az automatikus frissítéshez Windows, Linux vagy macOS x64 build szükséges." "Updater.Status.Unsupported": "Az automatikus frissítéshez Windows, Linux vagy macOS x64 build szükséges.",
"Options.Graphics": "Grafika",
"Options.Section.Rendering": "RENDERELÉS",
"Options.Section.Display": "KIJELZŐ",
"Options.RenderResolution.Label": "Belső felbontás",
"Options.RenderResolution.Desc": "A képernyőn kívüli célok renderelése a natívnál kisebb felbontáson, majd felskálázás megjelenítéskor. Az alacsonyabb értékek képminőséget cserélnek GPU-tartalékra; a következő indításkor lép érvénybe.",
"Options.RenderResolution.Native": "100% (natív)",
"Options.WindowMode.Label": "Ablakmód",
"Options.WindowMode.Desc": "Normál ablak, keret nélküli asztal vagy kizárólagos teljes képernyő.",
"Options.WindowMode.Windowed": "Ablakos",
"Options.WindowMode.Borderless": "Keret nélküli",
"Options.WindowMode.Exclusive": "Kizárólagos",
"Options.Resolution.Label": "Felbontás",
"Options.Resolution.Desc": "Kezdeti ablakméret vagy kizárólagos teljes képernyős felbontás.",
"Options.Display.Label": "Kijelző",
"Options.Display.Desc": "A középre igazításhoz és teljes képernyőhöz használt monitor.",
"Options.RefreshRate.Label": "Frissítési gyakoriság",
"Options.RefreshRate.Desc": "A kizárólagos teljes képernyő frissítési gyakorisága. Az automatikus mód a legközelebbi módot választja.",
"Options.RefreshRate.Automatic": "Automatikus",
"Options.Scaling.Label": "Méretezés",
"Options.Scaling.Desc": "A natív vendégkép méretezése a belső felbontás módosítása nélkül.",
"Options.Scaling.Fit": "Illesztés",
"Options.Scaling.Cover": "Kitöltés",
"Options.Scaling.Stretch": "Nyújtás",
"Options.Scaling.Integer": "Egész szám",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "FIFO megjelenítés használata képtörésmentes kimenethez.",
"Options.Hdr.Label": "HDR-kimenet",
"Options.Hdr.Desc": "HDR használata, ha a kiválasztott kijelző és grafikus backend támogatja. Az automatikus mód SDR-re vált vissza.",
"Options.Hdr.Auto": "Automatikus"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} giochi", "Page.GameCount.Other": "{0} giochi",
"Library.SearchWatermark": "Cerca nella libreria…", "Library.SearchWatermark": "Cerca nella libreria…",
"Library.AddFolder": " Aggiungi cartella", "Library.AddFolder": "Aggiungi cartella",
"Library.Rescan": "⟳ Riscansiona",
"Library.OpenFile": "Apri file…", "Library.OpenFile": "Apri file…",
"Library.Context.Launch": "Avvia", "Library.Context.Launch": "Avvia",
@@ -70,6 +69,8 @@
"Options.Language.Label": "Lingua dell'emulatore", "Options.Language.Label": "Lingua dell'emulatore",
"Options.Language.Desc": "Lingua utilizzata in tutto il launcher. Viene applicata immediatamente.", "Options.Language.Desc": "Lingua utilizzata in tutto il launcher. Viene applicata immediatamente.",
"Options.DefaultProfile.Label": "Nome profilo predefinito",
"Options.DefaultProfile.Desc": "Nome usato quando un gioco richiede l'inserimento di testo. Il valore predefinito è Sharp.",
"Common.On": "On", "Common.On": "On",
"Common.Off": "Off", "Common.Off": "Off",
@@ -144,6 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "Registra in console le allocazioni di memoria diretta e i relativi errori.\nUsalo quando un gioco si interrompe o si chiude durante l'avvio.", "Options.Env.LogDirectMemory.Desc": "Registra in console le allocazioni di memoria diretta e i relativi errori.\nUsalo quando un gioco si interrompe o si chiude durante l'avvio.",
"Options.Env.LogIo.Desc": "Registra in console l'apertura e la lettura dei file e la risoluzione dei percorsi.\nUsalo quando un gioco non trova i propri file di dati durante l'avvio.", "Options.Env.LogIo.Desc": "Registra in console l'apertura e la lettura dei file e la risoluzione dei percorsi.\nUsalo quando un gioco non trova i propri file di dati durante l'avvio.",
"Options.Env.LogNp.Desc": "Registra in console le chiamate alla libreria NP (PlayStation Network).", "Options.Env.LogNp.Desc": "Registra in console le chiamate alla libreria NP (PlayStation Network).",
"Options.Env.GuestImageCpuSync.Desc": "Ricarica le superfici guest riscritte dal codice CPU del gioco.\nLasciare disattivato normalmente. Attivare per i titoli le cui superfici disegnate dalla CPU non raggiungono mai lo schermo.\nCosta prestazioni e causa regressioni in alcuni titoli, come GTA V.",
"Common.Save": "Salva", "Common.Save": "Salva",
"Common.Cancel": "Annulla", "Common.Cancel": "Annulla",
"PerGame.Title": "Impostazioni per gioco — {0} ({1})", "PerGame.Title": "Impostazioni per gioco — {0} ({1})",
@@ -158,7 +160,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Unisciti alla community, ricevi supporto e segui lo sviluppo.", "About.Discord.Desc": "Unisciti alla community, ricevi supporto e segui lo sviluppo.",
"About.GithubButton": "Contribuisci su GitHub!", "About.GithubButton": "Contribuisci su GitHub!",
"About.DiscordButton": "Unisciti al nostro Discord!", "About.DiscordComingSoon": "Prossimamente",
"Updater.Auto.Label": "Controlla aggiornamenti all'avvio", "Updater.Auto.Label": "Controlla aggiornamenti all'avvio",
"Updater.Auto.Desc": "Interroga GitHub senza rallentare l'avvio.", "Updater.Auto.Desc": "Interroga GitHub senza rallentare l'avvio.",
"Updater.Label": "Aggiornamenti", "Updater.Label": "Aggiornamenti",
@@ -173,5 +175,34 @@
"Updater.Status.Timeout": "Il controllo degli aggiornamenti è scaduto dopo 10 secondi.", "Updater.Status.Timeout": "Il controllo degli aggiornamenti è scaduto dopo 10 secondi.",
"Updater.Status.Failed": "Impossibile controllare gli aggiornamenti.", "Updater.Status.Failed": "Impossibile controllare gli aggiornamenti.",
"Updater.Status.ChecksumFailed": "L'aggiornamento scaricato non ha superato la verifica SHA-256.", "Updater.Status.ChecksumFailed": "L'aggiornamento scaricato non ha superato la verifica SHA-256.",
"Updater.Status.Unsupported": "L'aggiornamento automatico richiede un build x64 per Windows, Linux o macOS." "Updater.Status.Unsupported": "L'aggiornamento automatico richiede un build x64 per Windows, Linux o macOS.",
"Options.Graphics": "Grafica",
"Options.Section.Rendering": "RENDERING",
"Options.Section.Display": "SCHERMO",
"Options.RenderResolution.Label": "Risoluzione interna",
"Options.RenderResolution.Desc": "Renderizza i target fuori schermo sotto la risoluzione nativa e li ridimensiona in fase di presentazione. Valori inferiori sacrificano la qualità dell'immagine per lasciare margine alla GPU; ha effetto al prossimo avvio.",
"Options.RenderResolution.Native": "100% (nativa)",
"Options.WindowMode.Label": "Modalità finestra",
"Options.WindowMode.Desc": "Finestra normale, desktop senza bordi o schermo intero esclusivo.",
"Options.WindowMode.Windowed": "In finestra",
"Options.WindowMode.Borderless": "Senza bordi",
"Options.WindowMode.Exclusive": "Esclusiva",
"Options.Resolution.Label": "Risoluzione",
"Options.Resolution.Desc": "Dimensione iniziale della finestra o risoluzione dello schermo intero esclusivo.",
"Options.Display.Label": "Schermo",
"Options.Display.Desc": "Monitor utilizzato per il centraggio e lo schermo intero.",
"Options.RefreshRate.Label": "Frequenza di aggiornamento",
"Options.RefreshRate.Desc": "Frequenza di aggiornamento dello schermo intero esclusivo. La modalità automatica seleziona la modalità più vicina.",
"Options.RefreshRate.Automatic": "Automatica",
"Options.Scaling.Label": "Ridimensionamento",
"Options.Scaling.Desc": "Ridimensiona l'immagine nativa del sistema guest senza modificarne la risoluzione interna.",
"Options.Scaling.Fit": "Adatta",
"Options.Scaling.Cover": "Riempi",
"Options.Scaling.Stretch": "Estendi",
"Options.Scaling.Integer": "Intero",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Usa la presentazione FIFO per evitare lo screen tearing.",
"Options.Hdr.Label": "Output HDR",
"Options.Hdr.Desc": "Usa HDR quando lo schermo selezionato e il backend grafico lo supportano. La modalità automatica torna a SDR.",
"Options.Hdr.Auto": "Automatico"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "ゲーム {0}本", "Page.GameCount.Other": "ゲーム {0}本",
"Library.SearchWatermark": "ライブラリを検索…", "Library.SearchWatermark": "ライブラリを検索…",
"Library.AddFolder": " フォルダーを追加", "Library.AddFolder": "フォルダーを追加",
"Library.Rescan": "⟳ 再スキャン",
"Library.OpenFile": "ファイルを開く…", "Library.OpenFile": "ファイルを開く…",
"Library.Context.Launch": "起動", "Library.Context.Launch": "起動",
@@ -67,6 +66,8 @@
"Options.Language.Label": "エミュレータの言語", "Options.Language.Label": "エミュレータの言語",
"Options.Language.Desc": "ランチャー全体で使用される言語。変更はすぐに適用されます。", "Options.Language.Desc": "ランチャー全体で使用される言語。変更はすぐに適用されます。",
"Options.DefaultProfile.Label": "既定のプロフィール名",
"Options.DefaultProfile.Desc": "ゲームがテキスト入力を要求したときに使用する名前です。既定値は Sharp です。",
"Common.On": "オン", "Common.On": "オン",
"Common.Off": "オフ", "Common.Off": "オフ",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "ダイレクトメモリの割り当てと失敗をコンソールに記録します。\nゲームが起動中に中断・終了する場合に使用してください。", "Options.Env.LogDirectMemory.Desc": "ダイレクトメモリの割り当てと失敗をコンソールに記録します。\nゲームが起動中に中断・終了する場合に使用してください。",
"Options.Env.LogIo.Desc": "ファイルのオープン・読み込み・パス解決の動作をコンソールに記録します。\nゲームが起動中にデータファイルを見つけられない場合に使用してください。", "Options.Env.LogIo.Desc": "ファイルのオープン・読み込み・パス解決の動作をコンソールに記録します。\nゲームが起動中にデータファイルを見つけられない場合に使用してください。",
"Options.Env.LogNp.Desc": "NPPlayStation Network)ライブラリの呼び出しをコンソールに記録します。", "Options.Env.LogNp.Desc": "NPPlayStation Network)ライブラリの呼び出しをコンソールに記録します。",
"Options.Env.GuestImageCpuSync.Desc": "ゲーム自身の CPU コードが書き換えるゲスト表面を再アップロードします。\n通常はオフのままにしてください。CPU で描画した表面が画面に反映されないタイトルで有効にします。\n性能を犠牲にし、GTA V など一部のタイトルでは不具合が生じます。",
"Common.Save": "保存", "Common.Save": "保存",
"Common.Cancel": "キャンセル", "Common.Cancel": "キャンセル",
"PerGame.Title": "ゲームごとの設定 — {0} ({1})", "PerGame.Title": "ゲームごとの設定 — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "コミュニティに参加して、サポートを受けたり開発を追いかけたりしましょう。", "About.Discord.Desc": "コミュニティに参加して、サポートを受けたり開発を追いかけたりしましょう。",
"About.GithubButton": "GitHubで貢献しよう!", "About.GithubButton": "GitHubで貢献しよう!",
"About.DiscordButton": "Discordに参加しよう!", "About.DiscordComingSoon": "近日公開",
"Updater.Auto.Label": "起動時にアップデートを確認", "Updater.Auto.Label": "起動時にアップデートを確認",
"Updater.Auto.Desc": "起動を遅らせずにGitHubへ確認します。", "Updater.Auto.Desc": "起動を遅らせずにGitHubへ確認します。",
"Updater.Label": "アップデート", "Updater.Label": "アップデート",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "アップデートの確認が10秒でタイムアウトしました。", "Updater.Status.Timeout": "アップデートの確認が10秒でタイムアウトしました。",
"Updater.Status.Failed": "アップデートを確認できませんでした。", "Updater.Status.Failed": "アップデートを確認できませんでした。",
"Updater.Status.ChecksumFailed": "ダウンロードしたアップデートはSHA-256検証に失敗しました。", "Updater.Status.ChecksumFailed": "ダウンロードしたアップデートはSHA-256検証に失敗しました。",
"Updater.Status.Unsupported": "自動アップデートにはWindows、Linux、またはmacOSのx64ビルドが必要です。" "Updater.Status.Unsupported": "自動アップデートにはWindows、Linux、またはmacOSのx64ビルドが必要です。",
"Options.Graphics": "グラフィックス",
"Options.Section.Rendering": "レンダリング",
"Options.Section.Display": "ディスプレイ",
"Options.RenderResolution.Label": "内部解像度",
"Options.RenderResolution.Desc": "ネイティブ解像度より低い解像度でオフスクリーンターゲットを描画し、表示時にアップスケールします。値を下げると画質と引き換えにGPU負荷を軽減します。次回起動時に適用されます。",
"Options.RenderResolution.Native": "100%(ネイティブ)",
"Options.WindowMode.Label": "ウィンドウモード",
"Options.WindowMode.Desc": "通常ウィンドウ、デスクトップのボーダーレス、または排他フルスクリーン。",
"Options.WindowMode.Windowed": "ウィンドウ",
"Options.WindowMode.Borderless": "ボーダーレス",
"Options.WindowMode.Exclusive": "排他",
"Options.Resolution.Label": "解像度",
"Options.Resolution.Desc": "初期ウィンドウサイズまたは排他フルスクリーンの解像度。",
"Options.Display.Label": "ディスプレイ",
"Options.Display.Desc": "中央配置とフルスクリーンに使用するモニター。",
"Options.RefreshRate.Label": "リフレッシュレート",
"Options.RefreshRate.Desc": "排他フルスクリーンのリフレッシュレート。自動では最も近いモードを選択します。",
"Options.RefreshRate.Automatic": "自動",
"Options.Scaling.Label": "スケーリング",
"Options.Scaling.Desc": "内部解像度を変更せずにゲストのネイティブ画像を拡大縮小します。",
"Options.Scaling.Fit": "フィット",
"Options.Scaling.Cover": "カバー",
"Options.Scaling.Stretch": "引き伸ばし",
"Options.Scaling.Integer": "整数倍",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "ティアリングのない表示のためFIFOプレゼンテーションを使用します。",
"Options.Hdr.Label": "HDR出力",
"Options.Hdr.Desc": "選択したディスプレイとグラフィックスバックエンドが対応している場合にHDRを使用します。自動ではSDRにフォールバックします。",
"Options.Hdr.Auto": "自動"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "게임 {0}개", "Page.GameCount.Other": "게임 {0}개",
"Library.SearchWatermark": "라이브러리 검색…", "Library.SearchWatermark": "라이브러리 검색…",
"Library.AddFolder": " 폴더 추가", "Library.AddFolder": "폴더 추가",
"Library.Rescan": "⟳ 다시 스캔",
"Library.OpenFile": "파일 열기…", "Library.OpenFile": "파일 열기…",
"Library.Context.Launch": "실행", "Library.Context.Launch": "실행",
@@ -67,6 +66,8 @@
"Options.Language.Label": "에뮬레이터 언어", "Options.Language.Label": "에뮬레이터 언어",
"Options.Language.Desc": "런처 전체에 사용되는 언어입니다. 변경 사항은 즉시 적용됩니다.", "Options.Language.Desc": "런처 전체에 사용되는 언어입니다. 변경 사항은 즉시 적용됩니다.",
"Options.DefaultProfile.Label": "기본 프로필 이름",
"Options.DefaultProfile.Desc": "게임에서 텍스트 입력을 요청할 때 사용할 이름입니다. 기본값은 Sharp입니다.",
"Common.On": "켬", "Common.On": "켬",
"Common.Off": "끔", "Common.Off": "끔",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "다이렉트 메모리 할당과 실패를 콘솔에 기록합니다.\n게임이 부팅 중 중단되거나 종료될 때 사용하세요.", "Options.Env.LogDirectMemory.Desc": "다이렉트 메모리 할당과 실패를 콘솔에 기록합니다.\n게임이 부팅 중 중단되거나 종료될 때 사용하세요.",
"Options.Env.LogIo.Desc": "파일 열기, 읽기, 경로 확인 동작을 콘솔에 기록합니다.\n게임이 부팅 중 데이터 파일을 찾지 못할 때 사용하세요.", "Options.Env.LogIo.Desc": "파일 열기, 읽기, 경로 확인 동작을 콘솔에 기록합니다.\n게임이 부팅 중 데이터 파일을 찾지 못할 때 사용하세요.",
"Options.Env.LogNp.Desc": "NP(PlayStation Network) 라이브러리 호출을 콘솔에 기록합니다.", "Options.Env.LogNp.Desc": "NP(PlayStation Network) 라이브러리 호출을 콘솔에 기록합니다.",
"Options.Env.GuestImageCpuSync.Desc": "게임의 자체 CPU 코드가 다시 쓰는 게스트 표면을 다시 업로드합니다.\n평소에는 꺼 두세요. CPU로 그린 표면이 화면에 나타나지 않는 타이틀에서 켜세요.\n성능을 소모하며 GTA V 등 일부 타이틀에서는 문제가 생깁니다.",
"Common.Save": "저장", "Common.Save": "저장",
"Common.Cancel": "취소", "Common.Cancel": "취소",
"PerGame.Title": "게임별 설정 — {0} ({1})", "PerGame.Title": "게임별 설정 — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "디스코드", "About.Discord.Label": "디스코드",
"About.Discord.Desc": "커뮤니티에 참여해 지원을 받고 개발 소식을 확인하세요.", "About.Discord.Desc": "커뮤니티에 참여해 지원을 받고 개발 소식을 확인하세요.",
"About.GithubButton": "GitHub에서 기여하기!", "About.GithubButton": "GitHub에서 기여하기!",
"About.DiscordButton": "디스코드 참여하기!", "About.DiscordComingSoon": "곧 공개",
"Updater.Auto.Label": "시작 시 업데이트 확인", "Updater.Auto.Label": "시작 시 업데이트 확인",
"Updater.Auto.Desc": "시작을 지연시키지 않고 GitHub를 확인합니다.", "Updater.Auto.Desc": "시작을 지연시키지 않고 GitHub를 확인합니다.",
"Updater.Label": "업데이트", "Updater.Label": "업데이트",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "업데이트 확인이 10초 후 시간 초과되었습니다.", "Updater.Status.Timeout": "업데이트 확인이 10초 후 시간 초과되었습니다.",
"Updater.Status.Failed": "업데이트를 확인할 수 없습니다.", "Updater.Status.Failed": "업데이트를 확인할 수 없습니다.",
"Updater.Status.ChecksumFailed": "다운로드한 업데이트가 SHA-256 검증에 실패했습니다.", "Updater.Status.ChecksumFailed": "다운로드한 업데이트가 SHA-256 검증에 실패했습니다.",
"Updater.Status.Unsupported": "자동 업데이트에는 Windows, Linux 또는 macOS x64 빌드가 필요합니다." "Updater.Status.Unsupported": "자동 업데이트에는 Windows, Linux 또는 macOS x64 빌드가 필요합니다.",
"Options.Graphics": "그래픽",
"Options.Section.Rendering": "렌더링",
"Options.Section.Display": "디스플레이",
"Options.RenderResolution.Label": "내부 해상도",
"Options.RenderResolution.Desc": "네이티브 해상도보다 낮은 해상도로 오프스크린 대상을 렌더링한 뒤 표시할 때 업스케일합니다. 값이 낮을수록 화질을 희생해 GPU 여유를 확보하며 다음 실행부터 적용됩니다.",
"Options.RenderResolution.Native": "100% (네이티브)",
"Options.WindowMode.Label": "창 모드",
"Options.WindowMode.Desc": "일반 창, 데스크톱 테두리 없음 또는 독점 전체 화면.",
"Options.WindowMode.Windowed": "창",
"Options.WindowMode.Borderless": "테두리 없음",
"Options.WindowMode.Exclusive": "독점",
"Options.Resolution.Label": "해상도",
"Options.Resolution.Desc": "초기 창 크기 또는 독점 전체 화면 해상도.",
"Options.Display.Label": "디스플레이",
"Options.Display.Desc": "가운데 배치와 전체 화면에 사용할 모니터.",
"Options.RefreshRate.Label": "새로 고침 빈도",
"Options.RefreshRate.Desc": "독점 전체 화면의 새로 고침 빈도입니다. 자동은 가장 가까운 모드를 선택합니다.",
"Options.RefreshRate.Automatic": "자동",
"Options.Scaling.Label": "스케일링",
"Options.Scaling.Desc": "내부 해상도를 변경하지 않고 게스트의 네이티브 이미지를 확대 또는 축소합니다.",
"Options.Scaling.Fit": "맞춤",
"Options.Scaling.Cover": "채우기",
"Options.Scaling.Stretch": "늘이기",
"Options.Scaling.Integer": "정수배",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "티어링 없는 출력을 위해 FIFO 프레젠테이션을 사용합니다.",
"Options.Hdr.Label": "HDR 출력",
"Options.Hdr.Desc": "선택한 디스플레이와 그래픽 백엔드가 지원하는 경우 HDR을 사용합니다. 자동 모드는 SDR로 대체됩니다.",
"Options.Hdr.Auto": "자동"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} games", "Page.GameCount.Other": "{0} games",
"Library.SearchWatermark": "Zoeken in bibliotheek…", "Library.SearchWatermark": "Zoeken in bibliotheek…",
"Library.AddFolder": " Map toevoegen", "Library.AddFolder": "Map toevoegen",
"Library.Rescan": "⟳ Opnieuw scannen",
"Library.OpenFile": "Bestand openen…", "Library.OpenFile": "Bestand openen…",
"Library.Context.Launch": "Starten", "Library.Context.Launch": "Starten",
@@ -67,6 +66,8 @@
"Options.Language.Label": "Taal van de emulator", "Options.Language.Label": "Taal van de emulator",
"Options.Language.Desc": "Taal die in de hele launcher wordt gebruikt. Wordt direct toegepast.", "Options.Language.Desc": "Taal die in de hele launcher wordt gebruikt. Wordt direct toegepast.",
"Options.DefaultProfile.Label": "Standaardprofielnaam",
"Options.DefaultProfile.Desc": "Naam die wordt gebruikt wanneer een game om tekstinvoer vraagt. De standaardwaarde is Sharp.",
"Common.On": "Aan", "Common.On": "Aan",
"Common.Off": "Uit", "Common.Off": "Uit",
@@ -139,6 +140,7 @@
"Options.Env.LogDirectMemory.Desc": "Log directe geheugentoewijzingen en fouten naar de console.\nGebruik dit wanneer een game tijdens het opstarten afbreekt of afsluit.", "Options.Env.LogDirectMemory.Desc": "Log directe geheugentoewijzingen en fouten naar de console.\nGebruik dit wanneer een game tijdens het opstarten afbreekt of afsluit.",
"Options.Env.LogIo.Desc": "Log het openen en lezen van bestanden en het oplossen van paden naar de console.\nGebruik dit wanneer een game zijn databestanden niet kan vinden tijdens het opstarten.", "Options.Env.LogIo.Desc": "Log het openen en lezen van bestanden en het oplossen van paden naar de console.\nGebruik dit wanneer een game zijn databestanden niet kan vinden tijdens het opstarten.",
"Options.Env.LogNp.Desc": "Log NP-bibliotheekaanroepen (PlayStation Network) naar de console.", "Options.Env.LogNp.Desc": "Log NP-bibliotheekaanroepen (PlayStation Network) naar de console.",
"Options.Env.GuestImageCpuSync.Desc": "Gastoppervlakken opnieuw uploaden die de eigen CPU-code van de game herschrijft.\nNormaal uit laten. Inschakelen voor titels waarvan de door de CPU getekende oppervlakken nooit het scherm bereiken.\nKost prestaties en veroorzaakt regressies in sommige titels, zoals GTA V.",
"Common.Save": "Opslaan", "Common.Save": "Opslaan",
"Common.Cancel": "Annuleren", "Common.Cancel": "Annuleren",
"PerGame.Title": "Instellingen per game — {0} ({1})", "PerGame.Title": "Instellingen per game — {0} ({1})",
@@ -153,7 +155,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Word lid van de community, krijg ondersteuning en volg de ontwikkeling.", "About.Discord.Desc": "Word lid van de community, krijg ondersteuning en volg de ontwikkeling.",
"About.GithubButton": "Draag bij op GitHub!", "About.GithubButton": "Draag bij op GitHub!",
"About.DiscordButton": "Word lid van onze Discord!", "About.DiscordComingSoon": "Binnenkort",
"Updater.Auto.Label": "Bij het opstarten controleren op updates", "Updater.Auto.Label": "Bij het opstarten controleren op updates",
"Updater.Auto.Desc": "Controleert GitHub zonder het opstarten te vertragen.", "Updater.Auto.Desc": "Controleert GitHub zonder het opstarten te vertragen.",
"Updater.Label": "Updates", "Updater.Label": "Updates",
@@ -168,5 +170,34 @@
"Updater.Status.Timeout": "De updatecontrole is na 10 seconden verlopen.", "Updater.Status.Timeout": "De updatecontrole is na 10 seconden verlopen.",
"Updater.Status.Failed": "Kon niet controleren op updates.", "Updater.Status.Failed": "Kon niet controleren op updates.",
"Updater.Status.ChecksumFailed": "De gedownloade update is niet door de SHA-256-verificatie gekomen.", "Updater.Status.ChecksumFailed": "De gedownloade update is niet door de SHA-256-verificatie gekomen.",
"Updater.Status.Unsupported": "Automatisch updaten vereist een x64-build voor Windows, Linux of macOS." "Updater.Status.Unsupported": "Automatisch updaten vereist een x64-build voor Windows, Linux of macOS.",
"Options.Graphics": "Grafisch",
"Options.Section.Rendering": "RENDERING",
"Options.Section.Display": "BEELDSCHERM",
"Options.RenderResolution.Label": "Interne resolutie",
"Options.RenderResolution.Desc": "Render offscreen-doelen onder de oorspronkelijke resolutie en schaal ze bij presentatie op. Lagere waarden ruilen beeldkwaliteit in voor GPU-marge; wordt bij de volgende start toegepast.",
"Options.RenderResolution.Native": "100% (native)",
"Options.WindowMode.Label": "Venstermodus",
"Options.WindowMode.Desc": "Normaal venster, randloos bureaublad of exclusief volledig scherm.",
"Options.WindowMode.Windowed": "Venster",
"Options.WindowMode.Borderless": "Randloos",
"Options.WindowMode.Exclusive": "Exclusief",
"Options.Resolution.Label": "Resolutie",
"Options.Resolution.Desc": "Initiële venstergrootte of resolutie voor exclusief volledig scherm.",
"Options.Display.Label": "Beeldscherm",
"Options.Display.Desc": "Monitor die wordt gebruikt voor centrering en volledig scherm.",
"Options.RefreshRate.Label": "Verversingssnelheid",
"Options.RefreshRate.Desc": "Verversingssnelheid voor exclusief volledig scherm. Automatisch selecteert de dichtstbijzijnde modus.",
"Options.RefreshRate.Automatic": "Automatisch",
"Options.Scaling.Label": "Schaling",
"Options.Scaling.Desc": "Schaal de oorspronkelijke gastafbeelding zonder de interne resolutie te wijzigen.",
"Options.Scaling.Fit": "Passend",
"Options.Scaling.Cover": "Vullend",
"Options.Scaling.Stretch": "Uitrekken",
"Options.Scaling.Integer": "Geheel getal",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Gebruik FIFO-presentatie voor uitvoer zonder tearing.",
"Options.Hdr.Label": "HDR-uitvoer",
"Options.Hdr.Desc": "Gebruik HDR wanneer het geselecteerde beeldscherm en de grafische backend dit ondersteunen. Automatisch valt terug op SDR.",
"Options.Hdr.Auto": "Automatisch"
} }
+35 -4
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} jogos", "Page.GameCount.Other": "{0} jogos",
"Library.SearchWatermark": "Pesquisar biblioteca…", "Library.SearchWatermark": "Pesquisar biblioteca…",
"Library.AddFolder": " Adicionar pasta", "Library.AddFolder": "Adicionar pasta",
"Library.Rescan": "⟳ Reanalisar",
"Library.OpenFile": "Abrir ficheiro…", "Library.OpenFile": "Abrir ficheiro…",
"Library.Context.Launch": "Iniciar", "Library.Context.Launch": "Iniciar",
@@ -35,6 +34,7 @@
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e as respetivas traduções SPIR-V para a pasta shader-dumps.\nUtilize ao reportar problemas de shaders ou renderização.", "Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e as respetivas traduções SPIR-V para a pasta shader-dumps.\nUtilize ao reportar problemas de shaders ou renderização.",
"Options.Env.LogDirectMemory.Desc": "Regista alocações de memória direta e falhas na consola.\nUtilize quando um jogo aborta ou fecha durante o arranque.", "Options.Env.LogDirectMemory.Desc": "Regista alocações de memória direta e falhas na consola.\nUtilize quando um jogo aborta ou fecha durante o arranque.",
"Options.Env.LogNp.Desc": "Regista chamadas da biblioteca NP (PlayStation Network) na consola.", "Options.Env.LogNp.Desc": "Regista chamadas da biblioteca NP (PlayStation Network) na consola.",
"Options.Env.GuestImageCpuSync.Desc": "Recarrega as superfícies do convidado que o próprio código de CPU do jogo reescreve.\nDeixar desativado normalmente. Ativar para títulos cujas superfícies desenhadas pela CPU nunca chegam ao ecrã.\nCusta desempenho e causa regressões em alguns títulos, como GTA V.",
"Options.Section.Emulation": "EMULAÇÃO", "Options.Section.Emulation": "EMULAÇÃO",
"Options.Section.Logging": "REGISTOS", "Options.Section.Logging": "REGISTOS",
"Options.Section.Launcher": "LANÇADOR", "Options.Section.Launcher": "LANÇADOR",
@@ -76,6 +76,8 @@
"Options.Language.Label": "Idioma do emulador", "Options.Language.Label": "Idioma do emulador",
"Options.Language.Desc": "Idioma utilizado em todo o lançador. Aplica-se de imediato.", "Options.Language.Desc": "Idioma utilizado em todo o lançador. Aplica-se de imediato.",
"Options.DefaultProfile.Label": "Nome de perfil predefinido",
"Options.DefaultProfile.Desc": "Nome utilizado quando um jogo solicita a introdução de texto. O valor predefinido é Sharp.",
"Common.On": "Ativado", "Common.On": "Ativado",
"Common.Off": "Desativado", "Common.Off": "Desativado",
@@ -142,7 +144,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Junte-se à comunidade, obtenha suporte e acompanhe o desenvolvimento.", "About.Discord.Desc": "Junte-se à comunidade, obtenha suporte e acompanhe o desenvolvimento.",
"About.GithubButton": "Contribua no GitHub!", "About.GithubButton": "Contribua no GitHub!",
"About.DiscordButton": "Junte-se ao nosso Discord!", "About.DiscordComingSoon": "Em breve",
"Library.Context.GameSettings": "Definições do jogo…", "Library.Context.GameSettings": "Definições do jogo…",
"Options.Env.WritableApp0.Desc": "Permitir que os jogos criem e escrevam ficheiros dentro da sua pasta de instalação.\nNecessário para dumps não empacotados que escrevem os seus dados guardados ou configurações em /app0.", "Options.Env.WritableApp0.Desc": "Permitir que os jogos criem e escrevam ficheiros dentro da sua pasta de instalação.\nNecessário para dumps não empacotados que escrevem os seus dados guardados ou configurações em /app0.",
@@ -169,5 +171,34 @@
"Updater.Status.Timeout": "A verificação de atualizações expirou após 10 segundos.", "Updater.Status.Timeout": "A verificação de atualizações expirou após 10 segundos.",
"Updater.Status.Failed": "Não foi possível procurar atualizações.", "Updater.Status.Failed": "Não foi possível procurar atualizações.",
"Updater.Status.ChecksumFailed": "A atualização transferida falhou a verificação SHA-256.", "Updater.Status.ChecksumFailed": "A atualização transferida falhou a verificação SHA-256.",
"Updater.Status.Unsupported": "A atualização automática requer um build x64 para Windows, Linux ou macOS." "Updater.Status.Unsupported": "A atualização automática requer um build x64 para Windows, Linux ou macOS.",
"Options.Graphics": "Gráficos",
"Options.Section.Rendering": "RENDERIZAÇÃO",
"Options.Section.Display": "ECRÃ",
"Options.RenderResolution.Label": "Resolução interna",
"Options.RenderResolution.Desc": "Renderiza alvos fora do ecrã abaixo da resolução nativa e amplia-os na apresentação. Valores inferiores trocam qualidade de imagem por margem da GPU; entra em vigor no próximo arranque.",
"Options.RenderResolution.Native": "100% (nativa)",
"Options.WindowMode.Label": "Modo de janela",
"Options.WindowMode.Desc": "Janela normal, ambiente de trabalho sem margens ou ecrã inteiro exclusivo.",
"Options.WindowMode.Windowed": "Em janela",
"Options.WindowMode.Borderless": "Sem margens",
"Options.WindowMode.Exclusive": "Exclusivo",
"Options.Resolution.Label": "Resolução",
"Options.Resolution.Desc": "Tamanho inicial da janela ou resolução de ecrã inteiro exclusivo.",
"Options.Display.Label": "Ecrã",
"Options.Display.Desc": "Monitor utilizado para centrar e apresentar em ecrã inteiro.",
"Options.RefreshRate.Label": "Taxa de atualização",
"Options.RefreshRate.Desc": "Taxa de atualização do ecrã inteiro exclusivo. O modo automático seleciona o modo mais próximo.",
"Options.RefreshRate.Automatic": "Automática",
"Options.Scaling.Label": "Escala",
"Options.Scaling.Desc": "Dimensiona a imagem nativa do sistema convidado sem alterar a respetiva resolução interna.",
"Options.Scaling.Fit": "Ajustar",
"Options.Scaling.Cover": "Preencher",
"Options.Scaling.Stretch": "Esticar",
"Options.Scaling.Integer": "Inteira",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Utiliza apresentação FIFO para evitar cortes na imagem.",
"Options.Hdr.Label": "Saída HDR",
"Options.Hdr.Desc": "Utiliza HDR quando o ecrã selecionado e o backend gráfico o suportam. O modo automático regressa a SDR.",
"Options.Hdr.Auto": "Automático"
} }
+43 -9
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "Игр: {0}", "Page.GameCount.Other": "Игр: {0}",
"Library.SearchWatermark": "Поиск…", "Library.SearchWatermark": "Поиск…",
"Library.AddFolder": " Добавить папку", "Library.AddFolder": "Добавить папку",
"Library.Rescan": "⟳ Сканировать",
"Library.OpenFile": "Открыть файл…", "Library.OpenFile": "Открыть файл…",
"Library.Context.Launch": "Запустить", "Library.Context.Launch": "Запустить",
@@ -38,9 +37,40 @@
"Options.Env.LogDirectMemory.Desc": "Выводить в консоль выделения прямой памяти и ошибки выделения.\nИспользуйте, если игра аварийно завершает работу или закрывается при запуске.", "Options.Env.LogDirectMemory.Desc": "Выводить в консоль выделения прямой памяти и ошибки выделения.\nИспользуйте, если игра аварийно завершает работу или закрывается при запуске.",
"Options.Env.LogIo.Desc": "Выводить в консоль операции открытия и чтения файлов, а также разрешение путей.\nИспользуйте, если игра не может найти файлы данных при запуске.", "Options.Env.LogIo.Desc": "Выводить в консоль операции открытия и чтения файлов, а также разрешение путей.\nИспользуйте, если игра не может найти файлы данных при запуске.",
"Options.Env.LogNp.Desc": "Выводить в консоль вызовы библиотеки NP (PlayStation Network).", "Options.Env.LogNp.Desc": "Выводить в консоль вызовы библиотеки NP (PlayStation Network).",
"Options.Env.GuestImageCpuSync.Desc": "Повторно загружать гостевые поверхности, которые переписывает собственный код ЦП игры.\nОбычно оставляйте выключенным. Включайте для игр, чьи отрисованные ЦП поверхности не попадают на экран.\nСнижает производительность и вызывает регрессии в некоторых играх, например в GTA V.",
"Options.Section.Emulation": "ЭМУЛЯЦИЯ", "Options.Section.Emulation": "ЭМУЛЯЦИЯ",
"Options.Section.Logging": "ЛОГГИРОВАНИЕ", "Options.Section.Logging": "ЛОГГИРОВАНИЕ",
"Options.Section.Launcher": "ЛАУНЧЕР", "Options.Section.Launcher": "ЛАУНЧЕР",
"Options.Section.Rendering": "РЕНДЕРИНГ",
"Options.Section.Display": "ЭКРАН",
"Options.Graphics": "Графика",
"Options.RenderResolution.Label": "Внутреннее разрешение",
"Options.RenderResolution.Desc": "Рендерить внеэкранные буферы ниже нативного разрешения и масштабировать при выводе. Меньшие значения снижают качество изображения, но уменьшают нагрузку на GPU; применяется при следующем запуске.",
"Options.RenderResolution.Native": "100% (нативное)",
"Options.WindowMode.Label": "Режим окна",
"Options.WindowMode.Desc": "Обычное окно, безрамочный режим рабочего стола или эксклюзивный полноэкранный режим.",
"Options.WindowMode.Windowed": "Оконный",
"Options.WindowMode.Borderless": "Без рамки",
"Options.WindowMode.Exclusive": "Эксклюзивный",
"Options.Resolution.Label": "Разрешение",
"Options.Resolution.Desc": "Начальный размер окна или разрешение эксклюзивного полноэкранного режима.",
"Options.Display.Label": "Монитор",
"Options.Display.Desc": "Монитор, используемый для центрирования окна и полноэкранного режима.",
"Options.RefreshRate.Label": "Частота обновления",
"Options.RefreshRate.Desc": "Частота обновления эксклюзивного полноэкранного режима. Автоматический режим выбирает ближайшее значение.",
"Options.RefreshRate.Automatic": "Автоматически",
"Options.Scaling.Label": "Масштабирование",
"Options.Scaling.Desc": "Масштабировать нативное изображение игры без изменения внутреннего разрешения.",
"Options.Scaling.Fit": "Вписать",
"Options.Scaling.Cover": "Заполнить",
"Options.Scaling.Stretch": "Растянуть",
"Options.Scaling.Integer": "Целочисленное",
"Options.VSync.Label": "VSync",
"Options.VSync.Desc": "Использовать режим представления FIFO для вывода без разрывов изображения.",
"Options.Hdr.Label": "HDR-вывод",
"Options.Hdr.Desc": "Использовать HDR, если выбранный монитор и графический бэкенд его поддерживают. Автоматический режим при необходимости переключается на SDR.",
"Options.Hdr.Auto": "Авто",
"Options.CpuEngine.Label": "Движок ЦП", "Options.CpuEngine.Label": "Движок ЦП",
"Options.CpuEngine.Desc": "Движок выполнения, используемый для запуска игрового кода.", "Options.CpuEngine.Desc": "Движок выполнения, используемый для запуска игрового кода.",
@@ -51,12 +81,12 @@
"Options.LogLevel.Label": "Уровень логгирования", "Options.LogLevel.Label": "Уровень логгирования",
"Options.LogLevel.Desc": "Подробность вывода в консоль эмулятора.", "Options.LogLevel.Desc": "Подробность вывода в консоль эмулятора.",
"Options.LogLevel.Trace": "Trace", "Options.LogLevel.Trace": "Трассировка",
"Options.LogLevel.Debug": "Debug", "Options.LogLevel.Debug": "Отладка",
"Options.LogLevel.Info": "Info", "Options.LogLevel.Info": "Информация",
"Options.LogLevel.Warning": "Warning", "Options.LogLevel.Warning": "Предупреждение",
"Options.LogLevel.Error": "Error", "Options.LogLevel.Error": "Ошибка",
"Options.LogLevel.Critical": "Critical", "Options.LogLevel.Critical": "Критический",
"Options.TraceImports.Label": "Лимит трассировки импортов", "Options.TraceImports.Label": "Лимит трассировки импортов",
"Options.TraceImports.Desc": "Трассировать первые N импортов в каждом модуле (0 - выключено).", "Options.TraceImports.Desc": "Трассировать первые N импортов в каждом модуле (0 - выключено).",
@@ -79,6 +109,8 @@
"Options.Language.Label": "Язык эмулятора", "Options.Language.Label": "Язык эмулятора",
"Options.Language.Desc": "Язык интерфейса лаунчера. Изменение применяется сразу.", "Options.Language.Desc": "Язык интерфейса лаунчера. Изменение применяется сразу.",
"Options.DefaultProfile.Label": "Имя профиля по умолчанию",
"Options.DefaultProfile.Desc": "Имя, используемое, когда игра запрашивает ввод текста. Значение по умолчанию — Sharp.",
"Common.On": "Включено", "Common.On": "Включено",
"Common.Off": "Выключено", "Common.Off": "Выключено",
@@ -87,6 +119,8 @@
"PerGame.Title": "Настройки игры — {0} ({1})", "PerGame.Title": "Настройки игры — {0} ({1})",
"PerGame.InheritNote": "Неотмеченные строки наследуют глобальные настройки.", "PerGame.InheritNote": "Неотмеченные строки наследуют глобальные настройки.",
"PerGame.Tab.General": "Основные",
"PerGame.Tab.Graphics": "Графика",
"PerGame.EnvToggles.Label": "Переключатели окружения", "PerGame.EnvToggles.Label": "Переключатели окружения",
"PerGame.EnvToggles.Desc": "Переопределить глобальный набор переключателей SHARPEMU_* для этой игры.", "PerGame.EnvToggles.Desc": "Переопределить глобальный набор переключателей SHARPEMU_* для этой игры.",
@@ -154,7 +188,7 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Присоединяйтесь к сообществу, получайте поддержку и следите за разработкой.", "About.Discord.Desc": "Присоединяйтесь к сообществу, получайте поддержку и следите за разработкой.",
"About.GithubButton": "Участвовать в разработке на GitHub!", "About.GithubButton": "Участвовать в разработке на GitHub!",
"About.DiscordButton": "Присоединиться к нашему Discord!", "About.DiscordComingSoon": "Скоро",
"Updater.Auto.Label": "Проверять обновления при запуске", "Updater.Auto.Label": "Проверять обновления при запуске",
"Updater.Auto.Desc": "Проверяет GitHub без задержки запуска.", "Updater.Auto.Desc": "Проверяет GitHub без задержки запуска.",
+17 -3
View File
@@ -7,8 +7,7 @@
"Page.GameCount.Other": "{0} oyun", "Page.GameCount.Other": "{0} oyun",
"Library.SearchWatermark": "Kütüphanede ara…", "Library.SearchWatermark": "Kütüphanede ara…",
"Library.AddFolder": " Klasör ekle", "Library.AddFolder": "Klasör ekle",
"Library.Rescan": "⟳ Yeniden tara",
"Library.OpenFile": "Dosya aç…", "Library.OpenFile": "Dosya aç…",
"Library.Context.Launch": "Başlat", "Library.Context.Launch": "Başlat",
@@ -173,6 +172,9 @@
"Options.Env.LogDirectMemory.Desc": "Doğrudan bellek tahsislerini ve hatalarını konsola günlükle.\nBir oyun açılış sırasında çöküyor veya kapanıyorsa kullanın.", "Options.Env.LogDirectMemory.Desc": "Doğrudan bellek tahsislerini ve hatalarını konsola günlükle.\nBir oyun açılış sırasında çöküyor veya kapanıyorsa kullanın.",
"Options.Env.LogIo.Desc": "Dosya açma, okuma ve yol çözümleme etkinliğini konsola günlükle.\nBir oyun açılışta veri dosyalarını bulamıyorsa kullanın.", "Options.Env.LogIo.Desc": "Dosya açma, okuma ve yol çözümleme etkinliğini konsola günlükle.\nBir oyun açılışta veri dosyalarını bulamıyorsa kullanın.",
"Options.Env.LogNp.Desc": "NP (PlayStation Network) kütüphane çağrılarını konsola günlükle.", "Options.Env.LogNp.Desc": "NP (PlayStation Network) kütüphane çağrılarını konsola günlükle.",
"Options.Env.GuestImageCpuSync.Desc": "Oyunun kendi CPU kodunun yeniden yazdığı misafir yüzeyleri tekrar yükler.\nNormalde kapalı bırakın. CPU ile çizilen yüzeyleri ekrana ulaşmayan oyunlarda açın.\nPerformansa mal olur ve GTA V gibi bazı oyunlarda soruna yol açar.",
"Options.DefaultProfile.Label": "Varsayilan profil adi",
"Options.DefaultProfile.Desc": "Oyun metin girisi istediginde kullanilacak ad. Varsayilan deger Sharp'tir.",
"Common.Save": "Kaydet", "Common.Save": "Kaydet",
"Common.Cancel": "İptal", "Common.Cancel": "İptal",
"PerGame.Title": "Oyuna özel ayarlar — {0} ({1})", "PerGame.Title": "Oyuna özel ayarlar — {0} ({1})",
@@ -189,5 +191,17 @@
"About.Discord.Label": "Discord", "About.Discord.Label": "Discord",
"About.Discord.Desc": "Topluluğa katılın, destek alın ve geliştirmeyi takip edin.", "About.Discord.Desc": "Topluluğa katılın, destek alın ve geliştirmeyi takip edin.",
"About.GithubButton": "GitHub'da katkıda bulun!", "About.GithubButton": "GitHub'da katkıda bulun!",
"About.DiscordButton": "Discord'umuza katıl!" "About.DiscordComingSoon": "Yakında",
"Options.Section.Rendering": "GÖRÜNTÜ İŞLEME",
"Options.RenderResolution.Label": "Dahili çözünürlük",
"Options.RenderResolution.Desc": "Ekran dışı hedefleri doğal çözünürlüğün altında işle ve sunum sırasında ölçeklendir. Daha düşük değerler GPU payı karşılığında görüntü kalitesini azaltır; bir sonraki başlatmada etkili olur.",
"Options.RenderResolution.Native": "%100 (doğal)",
"Options.WindowMode.Windowed": "Pencereli",
"Options.WindowMode.Borderless": "Kenarlıksız",
"Options.WindowMode.Exclusive": "Özel",
"Options.Scaling.Fit": "Sığdır",
"Options.Scaling.Cover": "Kapla",
"Options.Scaling.Stretch": "Uzat",
"Options.Scaling.Integer": "Tam sayı",
"Options.Hdr.Auto": "Otomatik"
} }
+9
View File
@@ -0,0 +1,9 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
/// <summary>
/// Base type for game cards and actions shown in the library rail.
/// </summary>
public abstract class LibraryTile;
+103
View File
@@ -0,0 +1,103 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace SharpEmu.GUI;
/// <summary>
/// Read-only view of the visible games with one persistent action tile at
/// the end. Game collection changes keep their original indices, so Avalonia
/// can update and virtualize the rail without rebuilding every item.
/// </summary>
public sealed class LibraryTileCollection : IReadOnlyList<LibraryTile>, IList, INotifyCollectionChanged
{
private readonly ObservableCollection<GameEntry> _games;
public LibraryTileCollection(ObservableCollection<GameEntry> games)
{
_games = games;
_games.CollectionChanged += OnGamesCollectionChanged;
}
public event NotifyCollectionChangedEventHandler? CollectionChanged;
public int Count => _games.Count + 1;
bool IList.IsFixedSize => false;
bool IList.IsReadOnly => true;
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
public LibraryTile this[int index]
{
get
{
if ((uint)index < (uint)_games.Count)
{
return _games[index];
}
if (index == _games.Count)
{
return AddFolderTile.Instance;
}
throw new ArgumentOutOfRangeException(nameof(index));
}
}
object? IList.this[int index]
{
get => this[index];
set => throw new NotSupportedException();
}
public IEnumerator<LibraryTile> GetEnumerator()
{
foreach (var game in _games)
{
yield return game;
}
yield return AddFolderTile.Instance;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
int IList.Add(object? value) => throw new NotSupportedException();
void IList.Clear() => throw new NotSupportedException();
bool IList.Contains(object? value) => ((IList)this).IndexOf(value) >= 0;
int IList.IndexOf(object? value) => value switch
{
GameEntry game => _games.IndexOf(game),
AddFolderTile => _games.Count,
_ => -1,
};
void IList.Insert(int index, object? value) => throw new NotSupportedException();
void IList.Remove(object? value) => throw new NotSupportedException();
void IList.RemoveAt(int index) => throw new NotSupportedException();
void ICollection.CopyTo(Array array, int index)
{
ArgumentNullException.ThrowIfNull(array);
foreach (var tile in this)
{
array.SetValue(tile, index++);
}
}
private void OnGamesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) =>
CollectionChanged?.Invoke(this, args);
}
+59 -83
View File
@@ -1,6 +1,8 @@
// Copyright (C) 2026 SharpEmu Emulator Project // Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json; using System.Text.Json;
namespace SharpEmu.GUI; namespace SharpEmu.GUI;
@@ -14,25 +16,50 @@ public sealed record LanguageInfo(string Code, string NativeName);
/// executable overrides the embedded copy for that code, so a translation /// executable overrides the embedded copy for that code, so a translation
/// fix or a brand-new language never needs a rebuild. /// fix or a brand-new language never needs a rebuild.
/// </summary> /// </summary>
public sealed class Localization public sealed class Localization : INotifyPropertyChanged
{ {
public static Localization Instance { get; } = new(); public static Localization Instance { get; } = new();
private const string EmbeddedResourcePrefix = "Languages."; private const string EmbeddedResourcePrefix = "Languages.";
private const string EmbeddedResourceSuffix = ".json"; private const string EmbeddedResourceSuffix = ".json";
private const string IndexerPropertyName = "Item";
private readonly string _languagesDirectory;
private Dictionary<string, string> _strings = new(); private Dictionary<string, string> _strings = new();
private Dictionary<string, string> _fallbackStrings = new(); private Dictionary<string, string> _fallbackStrings = new();
private string _currentCode = "en";
private Localization() : this(LanguagesDirectory)
private Localization()
{ {
} }
internal Localization(string languagesDirectory)
{
_languagesDirectory = languagesDirectory;
}
/// <summary>Directory holding optional *.json language overrides, next to the executable.</summary> /// <summary>Directory holding optional *.json language overrides, next to the executable.</summary>
public static string LanguagesDirectory => Path.Combine(AppContext.BaseDirectory, "Languages"); public static string LanguagesDirectory => Path.Combine(AppContext.BaseDirectory, "Languages");
public string CurrentCode { get; private set; } = "en"; public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>Exposes localized strings to XAML bindings by key.</summary>
public string this[string key] => Get(key);
public string CurrentCode
{
get => _currentCode;
private set
{
if (_currentCode == value)
{
return;
}
_currentCode = value;
OnPropertyChanged();
}
}
public string Get(string key) public string Get(string key)
{ {
@@ -67,7 +94,7 @@ public sealed class Localization
try try
{ {
foreach (var file in Directory.EnumerateFiles(LanguagesDirectory, "*.json")) foreach (var file in Directory.EnumerateFiles(_languagesDirectory, "*.json"))
{ {
var code = Path.GetFileNameWithoutExtension(file); var code = Path.GetFileNameWithoutExtension(file);
using var stream = File.OpenRead(file); using var stream = File.OpenRead(file);
@@ -84,47 +111,36 @@ public sealed class Localization
return result; return result;
} }
/// <summary>Loads a language by code (e.g. "en"): a loose override file first, then the embedded copy.</summary> /// <summary>
/// english is the fallback language /// Loads a language by code. Loose files overlay the embedded language,
/// while English supplies values missing from the selected language.
/// </summary>
public void Load(string code) public void Load(string code)
{ {
if (_fallbackStrings.Count == 0 && !string.Equals(code, "en", StringComparison.OrdinalIgnoreCase)) _fallbackStrings = LoadMergedLanguage("en");
_strings = string.Equals(code, "en", StringComparison.OrdinalIgnoreCase)
? _fallbackStrings
: LoadMergedLanguage(code);
CurrentCode = code;
OnPropertyChanged(IndexerPropertyName);
}
private Dictionary<string, string> LoadMergedLanguage(string code)
{
var merged = TryLoadEmbedded(code, out var embedded)
? embedded
: new Dictionary<string, string>();
if (TryLoadLooseFile(code, out var loose))
{ {
if (!TryLoadLooseFile("en", out var fallback) && !TryLoadEmbedded("en", out fallback)) foreach (var (key, value) in loose)
{ {
fallback = new Dictionary<string, string>(); merged[key] = value;
} }
_fallbackStrings = fallback;
}
else if (string.Equals(code, "en", StringComparison.OrdinalIgnoreCase))
{
if (TryLoadLooseFile("en", out var enDict) || TryLoadEmbedded("en", out enDict))
{
_strings = enDict;
_fallbackStrings = enDict;
}
else
{
_strings = new Dictionary<string, string>();
_fallbackStrings = new Dictionary<string, string>();
}
CurrentCode = "en";
return;
} }
// Load the requested language return merged;
if (TryLoadLooseFile(code, out var loaded) || TryLoadEmbedded(code, out loaded))
{
_strings = loaded;
}
else
{
if (_fallbackStrings.Count > 0)
_strings = new Dictionary<string, string>(_fallbackStrings);
else
_strings = new Dictionary<string, string>();
}
CurrentCode = code;
} }
private static IEnumerable<string> EmbeddedLanguageCodes() private static IEnumerable<string> EmbeddedLanguageCodes()
@@ -161,44 +177,12 @@ public sealed class Localization
return null; return null;
} }
private bool TryLoadLooseFile(string code)
{
try
{
var path = Path.Combine(LanguagesDirectory, $"{code}.json");
return File.Exists(path) && TryLoad(code, File.ReadAllText(path));
}
catch (Exception)
{
return false;
}
}
private bool TryLoadEmbedded(string code)
{
try
{
using var stream = OpenEmbeddedLanguageStream(code);
if (stream is null)
{
return false;
}
using var reader = new StreamReader(stream);
return TryLoad(code, reader.ReadToEnd());
}
catch (Exception)
{
return false;
}
}
private bool TryLoadLooseFile(string code, out Dictionary<string, string> result) private bool TryLoadLooseFile(string code, out Dictionary<string, string> result)
{ {
result = new Dictionary<string, string>(); result = new Dictionary<string, string>();
try try
{ {
var path = Path.Combine(LanguagesDirectory, $"{code}.json"); var path = Path.Combine(_languagesDirectory, $"{code}.json");
if (!File.Exists(path)) if (!File.Exists(path))
return false; return false;
@@ -243,14 +227,6 @@ public sealed class Localization
return true; return true;
} }
private bool TryLoad(string code, string json) private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{ => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
if (TryLoad(json, out var dict)) }
{
_strings = dict;
CurrentCode = code;
return true;
}
return false;
}
}
+61
View File
@@ -0,0 +1,61 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace SharpEmu.GUI;
/// <summary>
/// A stable settings value with a display label that can be refreshed when
/// the active UI language changes.
/// </summary>
public sealed class LocalizedChoice : INotifyPropertyChanged
{
private string _label;
private LocalizedChoice(string value, string label, string? localizationKey)
{
Value = value;
_label = label;
LocalizationKey = localizationKey;
}
public string Value { get; }
public string Label
{
get => _label;
private set
{
if (_label == value)
{
return;
}
_label = value;
OnPropertyChanged();
}
}
private string? LocalizationKey { get; }
public event PropertyChangedEventHandler? PropertyChanged;
public static LocalizedChoice FromKey(string value, string localizationKey) =>
new(value, localizationKey, localizationKey);
public static LocalizedChoice Literal(string value, string label) =>
new(value, label, null);
public void Refresh(Localization localization)
{
if (LocalizationKey is { } key)
{
Label = localization.Get(key);
}
}
private void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+9
View File
@@ -36,6 +36,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<AvaloniaResource Include="Assets\Fonts\MaterialSymbolsRounded-400.ttf" />
<AvaloniaResource Include="..\..\assets\images\SharpEmu.ico" Link="Assets/SharpEmu.ico" /> <AvaloniaResource Include="..\..\assets\images\SharpEmu.ico" Link="Assets/SharpEmu.ico" />
<AvaloniaResource Include="..\..\assets\images\github.png" Link="Assets/github.png" /> <AvaloniaResource Include="..\..\assets\images\github.png" Link="Assets/github.png" />
<AvaloniaResource Include="..\..\assets\images\discord.png" Link="Assets/discord.png" /> <AvaloniaResource Include="..\..\assets\images\discord.png" Link="Assets/discord.png" />
@@ -44,6 +45,14 @@ SPDX-License-Identifier: GPL-2.0-or-later
<AvaloniaResource Include="..\..\assets\images\pic0.png" Link="Assets/pic0.png" /> <AvaloniaResource Include="..\..\assets\images\pic0.png" Link="Assets/pic0.png" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSES\Apache-2.0.txt"
Link="licenses\Apache-2.0.txt"
CopyToOutputDirectory="PreserveNewest"
CopyToPublishDirectory="PreserveNewest"
TargetPath="licenses\Apache-2.0.txt" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Languages\*.json"> <EmbeddedResource Include="Languages\*.json">
<LogicalName>Languages.%(Filename)%(Extension)</LogicalName> <LogicalName>Languages.%(Filename)%(Extension)</LogicalName>
+15
View File
@@ -11,6 +11,21 @@ Window and text defaults shared by all launcher views.
<Setter Property="Foreground" Value="{StaticResource TextBrush}" /> <Setter Property="Foreground" Value="{StaticResource TextBrush}" />
</Style> </Style>
<Style Selector="TextBlock.materialSymbol">
<Setter Property="FontFamily" Value="{StaticResource MaterialSymbolsRounded}" />
<Setter Property="FontFeatures" Value="+liga" />
<Setter Property="FontSize" Value="18" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="LineHeight" Value="20" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Center" />
</Style>
<Style Selector="TextBlock.materialSymbol.compact">
<Setter Property="FontSize" Value="16" />
<Setter Property="LineHeight" Value="18" />
</Style>
<Style Selector="TextBlock.sectionTitle"> <Style Selector="TextBlock.sectionTitle">
<Setter Property="FontSize" Value="11" /> <Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" /> <Setter Property="FontWeight" Value="SemiBold" />
@@ -0,0 +1,36 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
Window chrome button sizing and interaction states.
-->
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style Selector="Button.windowChrome">
<Setter Property="Width" Value="46" />
<Setter Property="Height" Value="44" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="MinHeight" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="CornerRadius" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style Selector="TextBlock.windowChromeGlyph">
<Setter Property="IsHitTestVisible" Value="False" />
</Style>
<Style Selector="TextBlock.windowCloseGlyph">
<Setter Property="Margin" Value="0,-1,0,1" />
</Style>
<Style Selector="Button.windowChrome:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
</Style>
<Style Selector="Button.windowClose:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource DangerBrush}" />
<Setter Property="Foreground" Value="White" />
</Style>
</Styles>
+105 -16
View File
@@ -6,32 +6,121 @@ Cover-art library item states and motion.
<Styles xmlns="https://github.com/avaloniaui" <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style Selector="ListBox.tileGrid ListBoxItem"> <Style Selector="ListBox.tileGrid">
<Setter Property="Padding" Value="10" />
<Setter Property="Margin" Value="5" />
<Setter Property="CornerRadius" Value="14" />
<Setter Property="Background" Value="Transparent" /> <Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderThickness" Value="0" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem">
<Setter Property="Width" Value="160" />
<Setter Property="Height" Value="172" />
<Setter Property="Padding" Value="4" />
<Setter Property="Margin" Value="0,8,12,8" />
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Opacity" Value="0.72" />
<Setter Property="RenderTransformOrigin" Value="50%,50%" />
<Setter Property="RenderTransform" Value="translateY(0px)" /> <Setter Property="RenderTransform" Value="translateY(0px)" />
<Setter Property="Transitions"> <Setter Property="Transitions">
<Transitions> <Transitions>
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" /> <DoubleTransition Property="Opacity"
Duration="0:0:0.11"
Easing="QuadraticEaseOut" />
<TransformOperationsTransition Property="RenderTransform"
Duration="0:0:0.16"
Easing="CubicEaseOut" />
</Transitions> </Transitions>
</Setter> </Setter>
</Style> </Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover"> <Style Selector="ListBox.tileGrid ListBoxItem:pointerover,
<Setter Property="RenderTransform" Value="translateY(-3px)" /> ListBox.tileGrid ListBoxItem:selected">
<Setter Property="Opacity" Value="1" />
<Setter Property="RenderTransform" Value="translateY(-5px) scale(1.035)" />
</Style> </Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover /template/ ContentPresenter#PART_ContentPresenter"> <Style Selector="ListBox.tileGrid ListBoxItem /template/ ContentPresenter#PART_ContentPresenter,
<Setter Property="Background" Value="{StaticResource TileHoverBrush}" /> ListBox.tileGrid ListBoxItem:pointerover /template/ ContentPresenter#PART_ContentPresenter,
ListBox.tileGrid ListBoxItem:selected /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
</Style> </Style>
<Style Selector="ListBox.tileGrid ListBoxItem:selected /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource TileSelectedBrush}" /> <Style Selector="Border.libraryGameCard">
<Setter Property="BorderBrush" Value="{StaticResource AccentBrush}" /> <Setter Property="CornerRadius" Value="7" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BoxShadow" Value="0 12 28 0 #61000000" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="BorderBrush"
Duration="0:0:0.12"
Easing="QuadraticEaseOut" />
</Transitions>
</Setter>
</Style> </Style>
<Style Selector="ListBox.tileGrid ListBoxItem:selected:pointerover /template/ ContentPresenter#PART_ContentPresenter"> <Style Selector="ListBox.tileGrid ListBoxItem:selected Border.libraryGameCard">
<Setter Property="Background" Value="{StaticResource TileSelectedBrush}" /> <Setter Property="BorderBrush" Value="#E6FFFFFF" />
<Setter Property="BorderBrush" Value="{StaticResource AccentHoverBrush}" /> </Style>
<Style Selector="Border.libraryGameCard Border.coverClip">
<Setter Property="CornerRadius" Value="5" />
</Style>
<Style Selector="Border.addFolderTile">
<Setter Property="CornerRadius" Value="7" />
<Setter Property="Background" Value="#0CFFFFFF" />
<Setter Property="BorderBrush" Value="#2EFFFFFF" />
<Setter Property="BorderThickness" Value="1.5" />
<Setter Property="BoxShadow" Value="0 12 28 0 #3A000000" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
<BrushTransition Property="BorderBrush"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="Border.addFolderTileIcon">
<Setter Property="Width" Value="60" />
<Setter Property="Height" Value="60" />
<Setter Property="CornerRadius" Value="30" />
<Setter Property="Background" Value="#1BFFFFFF" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="TextBlock.addFolderGlyph">
<Setter Property="Foreground" Value="#A6FFFFFF" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Foreground"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="TextBlock.addFolderIconGlyph">
<Setter Property="RenderTransform" Value="translateY(-7px)" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover TextBlock.addFolderGlyph,
ListBox.tileGrid ListBoxItem:selected TextBlock.addFolderGlyph">
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover Border.addFolderTile,
ListBox.tileGrid ListBoxItem:selected Border.addFolderTile">
<Setter Property="Background" Value="#1AFFFFFF" />
<Setter Property="BorderBrush" Value="#55FFFFFF" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover Border.addFolderTileIcon,
ListBox.tileGrid ListBoxItem:selected Border.addFolderTileIcon">
<Setter Property="Background" Value="#2EFFFFFF" />
</Style> </Style>
</Styles> </Styles>
@@ -0,0 +1,229 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
Options page navigation, section transitions and content layout
-->
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SharpEmu.GUI"
xmlns:settingsControls="using:SharpEmu.GUI.Controls.Settings">
<Style Selector="Border.optionsNavSurface">
<Setter Property="Width" Value="244" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="VerticalAlignment" Value="Top" />
</Style>
<Style Selector="Border.optionsNavIndicator">
<Setter Property="Height" Value="54" />
<Setter Property="Margin" Value="0,3,0,0" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Background" Value="#13FFFFFF" />
<Setter Property="BorderBrush" Value="#E6FFFFFF" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BoxShadow" Value="0 8 24 0 #24000000" />
</Style>
<Style Selector="Button.optionsNav">
<Setter Property="Height" Value="61" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="Padding" Value="16,0" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="#8FFFFFFF" />
<Setter Property="FontSize" Value="14" />
<Setter Property="FontWeight" Value="Medium" />
<Setter Property="FocusAdorner" Value="{x:Null}" />
<Setter Property="RenderTransform" Value="none" />
</Style>
<Style Selector="Button.optionsNav /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="#8FFFFFFF" />
</Style>
<Style Selector="Button.optionsNav:pointerover /template/ ContentPresenter#PART_ContentPresenter,
Button.optionsNav:focus-visible /template/ ContentPresenter#PART_ContentPresenter,
Button.optionsNav.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.optionsNav:pressed">
<Setter Property="RenderTransform" Value="none" />
</Style>
<Style Selector="TextBlock.optionsNavIcon">
<Setter Property="Width" Value="20" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Padding" Value="0,0,0,5" />
<Setter Property="Foreground" Value="#8FFFFFFF" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Foreground"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="TextBlock.optionsNavLabel">
<Setter Property="FontSize" Value="14" />
<Setter Property="FontWeight" Value="Medium" />
<Setter Property="LineHeight" Value="20" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Padding" Value="0,0,0,4" />
<Setter Property="Foreground" Value="#8FFFFFFF" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Foreground"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button.optionsNav:pointerover TextBlock.optionsNavIcon,
Button.optionsNav:focus-visible TextBlock.optionsNavIcon,
Button.optionsNav.active TextBlock.optionsNavIcon">
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.optionsNav:pointerover TextBlock.optionsNavLabel,
Button.optionsNav:focus-visible TextBlock.optionsNavLabel,
Button.optionsNav.active TextBlock.optionsNavLabel">
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Border.optionsContentSurface">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ClipToBounds" Value="True" />
</Style>
<Style Selector="ScrollViewer.optionsSectionPanel">
<Setter Property="Opacity" Value="0" />
<Setter Property="RenderTransform" Value="translateY(22px)" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="VerticalScrollBarVisibility" Value="Auto" />
<Setter Property="Transitions">
<Transitions>
<DoubleTransition Property="Opacity"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
<TransformOperationsTransition Property="RenderTransform"
Duration="0:0:0.28"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="ScrollViewer.optionsSectionPanel.active">
<Setter Property="Opacity" Value="1" />
<Setter Property="RenderTransform" Value="translateY(0px)" />
</Style>
<Style Selector="Border.optionsGroup">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Padding" Value="0" />
</Style>
<Style Selector="Border.optionsInfoRow">
<Setter Property="MinHeight" Value="70" />
<Setter Property="Padding" Value="18,12" />
<Setter Property="CornerRadius" Value="14" />
<Setter Property="Background" Value="#06FFFFFF" />
<Setter Property="BorderBrush" Value="#0AFFFFFF" />
<Setter Property="BorderThickness" Value="1" />
</Style>
<Style Selector="local|SettingRow.optionRow:focus-within /template/ Border#PART_RowSurface">
<Setter Property="Background" Value="#0DFFFFFF" />
<Setter Property="BorderBrush" Value="#22FFFFFF" />
</Style>
<Style Selector="ComboBox.optionValue, settingsControls|SplitNumericUpDown.optionValue, TextBox.optionValue">
<Setter Property="Width" Value="190" />
<Setter Property="MinHeight" Value="44" />
<Setter Property="CornerRadius" Value="14" />
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="TextBox.optionValue">
<Setter Property="Padding" Value="17,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="TextAlignment" Value="Left" />
<Setter Property="ClipToBounds" Value="True" />
<Setter Property="FocusAdorner" Value="{x:Null}" />
</Style>
<Style Selector="TextBox.optionValue /template/ Border#PART_BorderElement">
<Setter Property="CornerRadius" Value="14" />
<Setter Property="ClipToBounds" Value="True" />
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<!-- The outer split-input surface owns hover and focus animation -->
<Style Selector="TextBox.splitNumericTextBox /template/ Border#PART_BorderElement,
TextBox.splitNumericTextBox:pointerover /template/ Border#PART_BorderElement,
TextBox.splitNumericTextBox:focus /template/ Border#PART_BorderElement">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="ToggleSwitch.optionToggle">
<Setter Property="Theme" Value="{StaticResource OptionToggleTheme}" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style Selector="Button.optionAction">
<Setter Property="MinWidth" Value="156" />
<Setter Property="MinHeight" Value="44" />
<Setter Property="Padding" Value="18,0" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="Medium" />
<Setter Property="FocusAdorner" Value="{x:Null}" />
</Style>
<Style Selector="Button.optionAction /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button.optionAction:pointerover /template/ ContentPresenter#PART_ContentPresenter,
Button.optionAction:focus-visible /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#20FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
</Style>
</Styles>
@@ -0,0 +1,76 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
Options-only control resources: compact toggle theme
-->
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTheme x:Key="OptionToggleTheme" TargetType="ToggleSwitch">
<Setter Property="Width" Value="46" />
<Setter Property="Height" Value="26" />
<Setter Property="MinWidth" Value="46" />
<Setter Property="MinHeight" Value="26" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="#2BFFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="FocusAdorner" Value="{x:Null}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="KnobTransitions">
<Transitions>
<DoubleTransition Property="Canvas.Left"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Setter>
<Setter Property="Template">
<ControlTemplate>
<Border x:Name="PART_Track"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Padding="3"
Background="{TemplateBinding Background}"
BorderThickness="0"
CornerRadius="13"
ClipToBounds="True">
<Canvas x:Name="PART_SwitchKnob"
Width="20"
Height="20"
HorizontalAlignment="Left"
VerticalAlignment="Center">
<Grid x:Name="PART_MovingKnobs"
Width="20"
Height="20"
Canvas.Left="0">
<Border x:Name="PART_Thumb"
Background="{StaticResource TextBrush}"
BorderThickness="0"
CornerRadius="10" />
</Grid>
</Canvas>
<Border.Transitions>
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.16"
Easing="CubicEaseOut" />
</Transitions>
</Border.Transitions>
</Border>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover /template/ Border#PART_Track">
<Setter Property="Background" Value="#38FFFFFF" />
</Style>
<Style Selector="^:checked /template/ Border#PART_Track">
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
</Style>
<Style Selector="^:checked:pointerover /template/ Border#PART_Track">
<Setter Property="Background" Value="{StaticResource AccentHoverBrush}" />
</Style>
<Style Selector="^:disabled /template/ Border#PART_Track">
<Setter Property="Opacity" Value="0.45" />
</Style>
</ControlTheme>
</ResourceDictionary>
@@ -8,26 +8,51 @@ Control theme for the shared launcher settings row.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SharpEmu.GUI"> xmlns:local="clr-namespace:SharpEmu.GUI">
<ControlTheme x:Key="{x:Type local:SettingRow}" TargetType="local:SettingRow"> <ControlTheme x:Key="{x:Type local:SettingRow}" TargetType="local:SettingRow">
<Setter Property="MinHeight" Value="70" />
<Setter Property="Template"> <Setter Property="Template">
<ControlTemplate> <ControlTemplate>
<Grid ColumnDefinitions="*,Auto"> <Border x:Name="PART_RowSurface"
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0"> Background="#06FFFFFF"
<TextBlock x:Name="PART_Label" Text="{TemplateBinding Label}" FontSize="13" /> BorderBrush="#0AFFFFFF"
<TextBlock Text="{TemplateBinding Description}" FontSize="11" BorderThickness="1"
Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" CornerRadius="14"
IsVisible="{Binding Description, RelativeSource={RelativeSource TemplatedParent}, Padding="18,12">
Converter={x:Static StringConverters.IsNotNullOrEmpty}}" /> <Grid ColumnDefinitions="*,Auto">
</StackPanel> <StackPanel VerticalAlignment="Center" Spacing="3" Margin="0,0,18,0">
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center"> <TextBlock x:Name="PART_Label"
<ToggleSwitch OnContent="Override" OffContent="Override" MinWidth="0" Text="{TemplateBinding Label}"
VerticalAlignment="Center" FontSize="14"
IsVisible="{TemplateBinding ShowOverride}" FontWeight="Medium"
IsChecked="{Binding IsOverridden, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" /> TextWrapping="Wrap"
<ContentPresenter x:Name="PART_Slot" Foreground="{StaticResource TextBrush}" />
Content="{TemplateBinding Content}" <TextBlock Text="{TemplateBinding Description}"
VerticalAlignment="Center" /> FontSize="11"
</StackPanel> FontWeight="Normal"
</Grid> Foreground="{StaticResource MutedBrush}"
LineHeight="16"
MaxWidth="690"
HorizontalAlignment="Left"
TextAlignment="Left"
TextWrapping="Wrap"
IsVisible="{Binding Description, RelativeSource={RelativeSource TemplatedParent},
Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<StackPanel Grid.Column="1"
Orientation="Horizontal"
Spacing="12"
VerticalAlignment="Center">
<ToggleSwitch OnContent="Override"
OffContent="Override"
MinWidth="0"
VerticalAlignment="Center"
IsVisible="{TemplateBinding ShowOverride}"
IsChecked="{Binding IsOverridden, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
<ContentPresenter x:Name="PART_Slot"
Content="{TemplateBinding Content}"
VerticalAlignment="Center" />
</StackPanel>
</Grid>
</Border>
</ControlTemplate> </ControlTemplate>
</Setter> </Setter>
</ControlTheme> </ControlTheme>
@@ -0,0 +1,197 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
Control themes for SplitNumericUpDown and its spinner parts
-->
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:settingsControls="using:SharpEmu.GUI.Controls.Settings">
<ControlTheme x:Key="SplitNumericRepeatButtonTheme" TargetType="RepeatButton">
<Setter Property="MinWidth" Value="0" />
<Setter Property="MinHeight" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="#B8FFFFFF" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="FocusAdorner" Value="{x:Null}" />
<Setter Property="Template">
<ControlTemplate>
<ContentPresenter x:Name="PART_ContentPresenter"
Background="{TemplateBinding Background}"
BorderBrush="Transparent"
BorderThickness="0"
Content="{TemplateBinding Content}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
<ContentPresenter.Transitions>
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
<BrushTransition Property="Foreground"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</ContentPresenter.Transitions>
</ContentPresenter>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#16FFFFFF" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="^:pressed /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#22FFFFFF" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="^:disabled /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Opacity" Value="0.45" />
</Style>
</ControlTheme>
<ControlTheme x:Key="SplitNumericSpinnerTheme" TargetType="ButtonSpinner">
<Setter Property="MinHeight" Value="44" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="#E8FFFFFF" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Grid ColumnDefinitions="*,52"
ColumnSpacing="8">
<Border x:Name="PART_ValueSurface"
MinHeight="{TemplateBinding MinHeight}"
Background="{TemplateBinding Background}"
BorderBrush="Transparent"
BorderThickness="0"
CornerRadius="14"
ClipToBounds="True">
<ContentPresenter x:Name="PART_ContentPresenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Padding="{TemplateBinding Padding}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
<Border.Transitions>
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Border.Transitions>
</Border>
<Border x:Name="PART_SpinnerSurface"
Grid.Column="1"
MinHeight="{TemplateBinding MinHeight}"
Background="{TemplateBinding Background}"
BorderBrush="Transparent"
BorderThickness="0"
CornerRadius="14"
ClipToBounds="True"
IsVisible="{TemplateBinding ShowButtonSpinner}">
<Grid RowDefinitions="*,*">
<RepeatButton x:Name="PART_IncreaseButton"
Grid.Row="0"
Theme="{StaticResource SplitNumericRepeatButtonTheme}"
IsTabStop="{TemplateBinding IsTabStop}">
<TextBlock Classes="materialSymbol compact"
Text="keyboard_arrow_up" />
</RepeatButton>
<RepeatButton x:Name="PART_DecreaseButton"
Grid.Row="1"
Theme="{StaticResource SplitNumericRepeatButtonTheme}"
IsTabStop="{TemplateBinding IsTabStop}">
<TextBlock Classes="materialSymbol compact"
Text="keyboard_arrow_down" />
</RepeatButton>
<Border Height="1"
Grid.RowSpan="2"
Background="#14FFFFFF"
VerticalAlignment="Center"
IsHitTestVisible="False" />
</Grid>
<Border.Transitions>
<Transitions>
<BrushTransition Property="Background"
Duration="0:0:0.18"
Easing="CubicEaseOut" />
</Transitions>
</Border.Transitions>
</Border>
</Grid>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover /template/ Border#PART_ValueSurface,
^:focus-within /template/ Border#PART_ValueSurface">
<Setter Property="Background" Value="#20FFFFFF" />
</Style>
<Style Selector="^:pointerover /template/ Border#PART_SpinnerSurface,
^:focus-within /template/ Border#PART_SpinnerSurface">
<Setter Property="Background" Value="#20FFFFFF" />
</Style>
</ControlTheme>
<ControlTheme x:Key="{x:Type settingsControls:SplitNumericUpDown}"
TargetType="settingsControls:SplitNumericUpDown">
<Setter Property="MinHeight" Value="44" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="#12FFFFFF" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="#E8FFFFFF" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Left" />
<Setter Property="Template">
<ControlTemplate>
<DataValidationErrors>
<ButtonSpinner x:Name="PART_Spinner"
Theme="{StaticResource SplitNumericSpinnerTheme}"
Background="{TemplateBinding Background}"
BorderBrush="Transparent"
BorderThickness="0"
IsTabStop="False"
Padding="0"
MinWidth="0"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
AllowSpin="{TemplateBinding AllowSpin}"
ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}">
<TextBox x:Name="PART_TextBox"
Classes="splitNumericTextBox"
MinHeight="{TemplateBinding MinHeight}"
MinWidth="0"
Margin="0"
Padding="17,0"
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="0"
Foreground="{TemplateBinding Foreground}"
PlaceholderText="{TemplateBinding PlaceholderText}"
PlaceholderForeground="{TemplateBinding PlaceholderForeground}"
IsReadOnly="{TemplateBinding IsReadOnly}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Text="{TemplateBinding Text}"
TextAlignment="{TemplateBinding TextAlignment}"
AcceptsReturn="False"
TextWrapping="NoWrap"
InnerLeftContent="{Binding InnerLeftContent, RelativeSource={RelativeSource TemplatedParent}}"
InnerRightContent="{Binding InnerRightContent, RelativeSource={RelativeSource TemplatedParent}}" />
</ButtonSpinner>
</DataValidationErrors>
</ControlTemplate>
</Setter>
</ControlTheme>
</ResourceDictionary>
+2
View File
@@ -6,6 +6,8 @@ Shared colors and brushes used throughout the launcher.
<ResourceDictionary xmlns="https://github.com/avaloniaui" <ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<FontFamily x:Key="MaterialSymbolsRounded">avares://SharpEmu.GUI/Assets/Fonts/MaterialSymbolsRounded-400.ttf#Material Symbols Rounded</FontFamily>
<Color x:Key="SystemAccentColor">#7C5CFC</Color> <Color x:Key="SystemAccentColor">#7C5CFC</Color>
<LinearGradientBrush x:Key="BgBrush" StartPoint="0%,0%" EndPoint="100%,100%"> <LinearGradientBrush x:Key="BgBrush" StartPoint="0%,0%" EndPoint="100%,100%">
@@ -0,0 +1,9 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
internal readonly record struct WindowMaximizeButtonState(
string Glyph,
string ToolTip,
string AutomationName);
+282 -12
View File
@@ -3,7 +3,7 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using SharpEmu.HLE; using SharpEmu.HLE;
using SharpEmu.Libs.Bink; using SharpEmu.Libs.Media;
using SharpEmu.Libs.Gpu; using SharpEmu.Libs.Gpu;
using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler;
using SharpEmu.Libs.Kernel; using SharpEmu.Libs.Kernel;
@@ -46,6 +46,9 @@ public static partial class AgcExports
private const uint ItNumInstances = 0x2F; private const uint ItNumInstances = 0x2F;
private const uint ItDrawIndexMultiAuto = 0x30; private const uint ItDrawIndexMultiAuto = 0x30;
private const uint ItDrawIndexOffset2 = 0x35; private const uint ItDrawIndexOffset2 = 0x35;
private const uint ItDrawIndexIndirectMulti = 0x38;
private const uint DrawIndexedIndirectArgsSize = 20;
private const uint DrawIndexedIndirectMaxScan = 1024;
private const uint ItWriteData = 0x37; private const uint ItWriteData = 0x37;
private const uint ItDispatchDirect = 0x15; private const uint ItDispatchDirect = 0x15;
private const uint ItDispatchIndirect = 0x16; private const uint ItDispatchIndirect = 0x16;
@@ -319,6 +322,7 @@ public static partial class AgcExports
private static int _tracedVertexRangeCount; private static int _tracedVertexRangeCount;
private static long _dcbWaitRegMemTraceCount; private static long _dcbWaitRegMemTraceCount;
private static long _createShaderTraceCount; private static long _createShaderTraceCount;
private static long _duplicateTargetTraceCount;
private static long _cbMetadataSkipTraceCount; private static long _cbMetadataSkipTraceCount;
private static long _packetPayloadTraceCount; private static long _packetPayloadTraceCount;
private static bool _tracedMissingPixelShaderBindings; private static bool _tracedMissingPixelShaderBindings;
@@ -1994,6 +1998,65 @@ public static partial class AgcExports
return ReturnPointer(ctx, drawCommand); return ReturnPointer(ctx, drawCommand);
} }
[SysAbiExport(
Nid = "1q1titRBL6o",
ExportName = "sceAgcDcbDrawIndirect",
Target = Generation.Gen5,
LibraryName = "libSceAgc")]
public static int DcbDrawIndirect(CpuContext ctx)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
var dataOffset = (uint)ctx[CpuRegister.Rsi];
var emit = Interlocked.Increment(ref _indirectDrawEmitCount);
if (emit <= 12 || emit % 250 == 0)
{
var rcx = ctx[CpuRegister.Rcx];
var dump = string.Empty;
for (var word = 0; word < 8; word++)
{
dump += TryReadUInt32(ctx, rcx + dataOffset + ((ulong)word * 4), out var raw)
? $" {raw}"
: " ?";
}
Console.Error.WriteLine(
$"[LOADER][WARN] agc.emit_indirect#{emit} buf=0x{commandBufferAddress:X16} " +
$"off=0x{dataOffset:X} rdx=0x{ctx[CpuRegister.Rdx]:X} rcx=0x{rcx:X} " +
$"r8=0x{ctx[CpuRegister.R8]:X} rcx_words:{dump}");
}
if (commandBufferAddress == 0)
{
Interlocked.Increment(ref _indirectDrawEmitRejectCount);
return ReturnPointer(ctx, 0);
}
if (!TryAllocateCommandDwords(ctx, commandBufferAddress, 5, out var drawCommand) ||
!TryWriteUInt32(ctx, drawCommand, Pm4(5, ItDrawIndirect, 0)) ||
!TryWriteUInt32(ctx, drawCommand + 4, dataOffset) ||
!TryWriteUInt32(ctx, drawCommand + 8, 0) ||
!TryWriteUInt32(ctx, drawCommand + 12, 0) ||
!TryWriteUInt32(ctx, drawCommand + 16, 0))
{
var rejects = Interlocked.Increment(ref _indirectDrawEmitRejectCount);
if (rejects <= 8 || rejects % 250 == 0)
{
Console.Error.WriteLine(
$"[LOADER][WARN] agc.emit_indirect_reject#{rejects} " +
$"buf=0x{commandBufferAddress:X16} reason=alloc_or_write");
}
return ReturnPointer(ctx, 0);
}
TraceAgc(
$"agc.dcb_draw_indirect buf=0x{commandBufferAddress:X16} " +
$"draw=0x{drawCommand:X16} offset=0x{dataOffset:X}");
return ReturnPointer(ctx, drawCommand);
}
[SysAbiExport( [SysAbiExport(
Nid = "Yw0jKSqop+E", Nid = "Yw0jKSqop+E",
ExportName = "sceAgcDcbDrawIndexAuto", ExportName = "sceAgcDcbDrawIndexAuto",
@@ -2052,6 +2115,39 @@ public static partial class AgcExports
return ReturnPointer(ctx, commandAddress); return ReturnPointer(ctx, commandAddress);
} }
[SysAbiExport(
Nid = "ypVBz4uPKcQ",
ExportName = "sceAgcDcbDrawIndexIndirectMulti",
Target = Generation.Gen5,
LibraryName = "libSceAgc")]
public static int DcbDrawIndexIndirectMulti(CpuContext ctx)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
var dataOffset = (uint)ctx[CpuRegister.Rsi];
var drawCount = (uint)ctx[CpuRegister.Rdx];
var stride = DrawIndexedIndirectArgsSize;
var modifier = (uint)ctx[CpuRegister.R8];
if (commandBufferAddress == 0 ||
!TryAllocateCommandDwords(ctx, commandBufferAddress, 8, out var commandAddress) ||
!TryWriteUInt32(ctx, commandAddress, Pm4(8, ItDrawIndexIndirectMulti, 0)) ||
!TryWriteUInt32(ctx, commandAddress + 4, dataOffset) ||
!TryWriteUInt32(ctx, commandAddress + 8, 0) ||
!TryWriteUInt32(ctx, commandAddress + 12, 0) ||
!TryWriteUInt32(ctx, commandAddress + 16, 0) ||
!TryWriteUInt32(ctx, commandAddress + 20, drawCount) ||
!TryWriteUInt32(ctx, commandAddress + 24, stride) ||
!TryWriteUInt32(ctx, commandAddress + 28, modifier))
{
return ReturnPointer(ctx, 0);
}
TraceAgc(
$"agc.dcb_draw_index_indirect_multi buf=0x{commandBufferAddress:X16} " +
$"cmd=0x{commandAddress:X16} offset=0x{dataOffset:X8} draws={drawCount} " +
$"stride={stride} modifier=0x{modifier:X8}");
return ReturnPointer(ctx, commandAddress);
}
[SysAbiExport( [SysAbiExport(
Nid = "mStuvI0zOtc", Nid = "mStuvI0zOtc",
ExportName = "sceAgcDcbDrawIndexIndirectGetSize", ExportName = "sceAgcDcbDrawIndexIndirectGetSize",
@@ -3812,6 +3908,7 @@ public static partial class AgcExports
if (TryReadSubmittedDrawCount( if (TryReadSubmittedDrawCount(
ctx, ctx,
gpuState,
state, state,
currentAddress, currentAddress,
length, length,
@@ -3835,7 +3932,8 @@ public static partial class AgcExports
var indexed = op is var indexed = op is
ItDrawIndex2 or ItDrawIndex2 or
ItDrawIndexOffset2 or ItDrawIndexOffset2 or
ItDrawIndexIndirect; ItDrawIndexIndirect or
ItDrawIndexIndirectMulti;
state.SawIndexedDraw |= indexed; state.SawIndexedDraw |= indexed;
TryTranslateGuestDraw(ctx, gpuState, state, indexCount, indexed); TryTranslateGuestDraw(ctx, gpuState, state, indexCount, indexed);
} }
@@ -4195,6 +4293,7 @@ public static partial class AgcExports
op is ItDispatchDirect or ItDispatchIndirect || op is ItDispatchDirect or ItDispatchIndirect ||
op is ItDrawIndirect or op is ItDrawIndirect or
ItDrawIndexIndirect or ItDrawIndexIndirect or
ItDrawIndexIndirectMulti or
ItDrawIndex2 or ItDrawIndex2 or
ItDrawIndexAuto or ItDrawIndexAuto or
ItDrawIndexMultiAuto or ItDrawIndexMultiAuto or
@@ -6164,8 +6263,24 @@ public static partial class AgcExports
} }
} }
private const int IndirectArgsFlushTimeoutMilliseconds = 250;
private static void FlushGpuWorkForIndirectArgs(SubmittedGpuState gpuState)
{
var pending = gpuState.WorkSequence;
if (pending == 0 || pending > long.MaxValue)
{
return;
}
GuestGpu.Current.WaitForGuestWork(
(long)pending,
IndirectArgsFlushTimeoutMilliseconds);
}
private static bool TryReadSubmittedDrawCount( private static bool TryReadSubmittedDrawCount(
CpuContext ctx, CpuContext ctx,
SubmittedGpuState gpuState,
SubmittedDcbState state, SubmittedDcbState state,
ulong packetAddress, ulong packetAddress,
uint packetLength, uint packetLength,
@@ -6196,17 +6311,89 @@ public static partial class AgcExports
drawCount = (control >> 21) & 0x7FFu; drawCount = (control >> 21) & 0x7FFu;
return true; return true;
case ItDrawIndirect or ItDrawIndexIndirect case ItDrawIndexIndirectMulti when packetLength >= 8 &&
when packetLength >= 5 && state.IndirectArgsAddress != 0: state.IndirectArgsAddress != 0:
if (!TryReadUInt32(ctx, packetAddress + 4, out var dataOffset)) if (!TryReadUInt32(ctx, packetAddress + 4, out var multiOffset) ||
!TryReadUInt32(ctx, packetAddress + 20, out var multiDraws) ||
!TryReadUInt32(ctx, packetAddress + 24, out var multiStride))
{ {
return false; return false;
} }
return TryReadUInt32(
ctx, if (multiStride < DrawIndexedIndirectArgsSize)
state.IndirectArgsAddress + dataOffset, {
out drawCount); multiStride = DrawIndexedIndirectArgsSize;
}
var multiTotal = 0UL;
var multiCapped = multiDraws == 0
? DrawIndexedIndirectMaxScan
: Math.Min(multiDraws, 4096u);
for (var draw = 0u; draw < multiCapped; draw++)
{
if (!TryReadUInt32(
ctx,
state.IndirectArgsAddress + multiOffset + ((ulong)draw * multiStride),
out var subCount))
{
break;
}
if (subCount == 0 && multiDraws == 0)
{
break;
}
multiTotal += subCount;
}
var multiProbe = Interlocked.Increment(ref _indirectMultiProbeCount);
if (multiProbe <= 12 || multiProbe % 250 == 0)
{
Console.Error.WriteLine(
$"[LOADER][WARN] agc.draw_multi#{multiProbe} args=0x{state.IndirectArgsAddress:X} " +
$"off=0x{multiOffset:X} draws={multiDraws} stride={multiStride} " +
$"total={multiTotal}");
}
drawCount = (uint)Math.Min(multiTotal, uint.MaxValue);
return drawCount != 0;
case ItDrawIndirect or ItDrawIndexIndirect:
var probe = Interlocked.Increment(ref _indirectDrawProbeCount);
if (!TryReadUInt32(ctx, packetAddress + 4, out var dataOffset))
{
dataOffset = 0xFFFFFFFFu;
}
var readable = packetLength >= 5 &&
state.IndirectArgsAddress != 0 &&
dataOffset != 0xFFFFFFFFu;
var resolved = readable &&
TryReadUInt32(
ctx,
state.IndirectArgsAddress + dataOffset,
out drawCount);
if (probe <= 12 || probe % 100 == 0)
{
var dump = string.Empty;
for (var word = 0; word < 8; word++)
{
dump += TryReadUInt32(
ctx,
state.IndirectArgsAddress + dataOffset + ((ulong)word * 4),
out var raw)
? $" {raw}"
: " ?";
}
Console.Error.WriteLine(
$"[LOADER][WARN] agc.draw_indirect#{probe} op=0x{op:X} len={packetLength} " +
$"args=0x{state.IndirectArgsAddress:X} off=0x{dataOffset:X} " +
$"resolved={resolved} count={drawCount} words:{dump}");
}
return resolved;
default: default:
return false; return false;
} }
@@ -8056,6 +8243,61 @@ public static partial class AgcExports
source.Format == destination.Format; source.Format == destination.Format;
} }
private static readonly HashSet<ulong> _renderTargetAddresses = new();
private static readonly HashSet<ulong> _sampledRenderTargets = new();
private static readonly object _renderTargetProbeGate = new();
private static long _renderTargetSampleTraceCount;
private static long _indirectDrawProbeCount;
private static long _indirectDrawEmitCount;
private static long _indirectDrawEmitRejectCount;
private static long _indirectMultiProbeCount;
private static void NoteRenderTargetAddress(ulong address)
{
if (address == 0)
{
return;
}
lock (_renderTargetProbeGate)
{
if (_renderTargetAddresses.Count < 512)
{
_renderTargetAddresses.Add(address);
}
}
}
private static void NoteSampledAddress(ulong address, uint format = 0, uint numberType = 0)
{
if (address == 0)
{
return;
}
bool firstTime;
int distinctTargets;
lock (_renderTargetProbeGate)
{
if (!_renderTargetAddresses.Contains(address))
{
return;
}
firstTime = _sampledRenderTargets.Add(address);
distinctTargets = _renderTargetAddresses.Count;
}
var count = Interlocked.Increment(ref _renderTargetSampleTraceCount);
if (firstTime || count % 2000 == 0)
{
var gpuResident = GuestGpu.Current.IsGpuGuestImageAvailable(address, format, numberType);
Console.Error.WriteLine(
$"[LOADER][WARN] agc.rt_sampled#{count} addr=0x{address:X} first={firstTime} " +
$"gpu_resident={gpuResident} fmt={format}/{numberType} known_targets={distinctTargets}");
}
}
private static IReadOnlyList<RenderTargetDescriptor> GetRenderTargets( private static IReadOnlyList<RenderTargetDescriptor> GetRenderTargets(
IReadOnlyDictionary<uint, uint> registers, IReadOnlyDictionary<uint, uint> registers,
bool includeMaskedTargets = false) bool includeMaskedTargets = false)
@@ -8082,6 +8324,13 @@ public static partial class AgcExports
continue; continue;
} }
if (targets.Exists(existing => existing.Address == address))
{
continue;
}
NoteRenderTargetAddress(address);
targets.Add(new RenderTargetDescriptor( targets.Add(new RenderTargetDescriptor(
slot, slot,
address, address,
@@ -8092,6 +8341,21 @@ public static partial class AgcExports
(attrib3 >> 14) & 0x1Fu)); (attrib3 >> 14) & 0x1Fu));
} }
if (targets.Count > 1 &&
targets.Select(t => t.Address).Distinct().Count() != targets.Count)
{
var dupCount = Interlocked.Increment(ref _duplicateTargetTraceCount);
if (dupCount <= 12 || dupCount % 500 == 0)
{
Console.Error.WriteLine(
$"[LOADER][WARN] agc.rt_duplicate#{dupCount} has_mask={hasTargetMask} " +
$"mask=0x{targetMask:X8} slots=[" +
string.Join(",", targets.Select(t =>
$"{t.Slot}:0x{t.Address:X}:m{(targetMask >> ((int)t.Slot * 4)) & 0xFu}")) +
"]");
}
}
return targets; return targets;
} }
@@ -9331,6 +9595,7 @@ public static partial class AgcExports
descriptor.Format, descriptor.Format,
descriptor.NumberType)) descriptor.NumberType))
{ {
NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture( texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
@@ -9410,6 +9675,7 @@ public static partial class AgcExports
$"tile={descriptor.TileMode} mip={mipLevel}"); $"tile={descriptor.TileMode} mip={mipLevel}");
} }
NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture( texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
@@ -9470,6 +9736,7 @@ public static partial class AgcExports
descriptor.Type, descriptor.Type,
textureDepth))) textureDepth)))
{ {
NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture( texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
@@ -9532,7 +9799,8 @@ public static partial class AgcExports
if (readAllLayers) if (readAllLayers)
{ {
texture = new GuestDrawTexture( NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
descriptor.Height, descriptor.Height,
@@ -9594,7 +9862,8 @@ public static partial class AgcExports
if (uploadedLayers == arrayLayers) if (uploadedLayers == arrayLayers)
{ {
texture = new GuestDrawTexture( NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
descriptor.Height, descriptor.Height,
@@ -9697,7 +9966,8 @@ public static partial class AgcExports
if (IsGpuDetileEquation(gpuDetileParams.Equation) && if (IsGpuDetileEquation(gpuDetileParams.Equation) &&
(long)elementsWide * elementsHigh * bytesPerElement <= source.Length) (long)elementsWide * elementsHigh * bytesPerElement <= source.Length)
{ {
texture = new GuestDrawTexture( NoteSampledAddress(descriptor.Address, descriptor.Format, descriptor.NumberType);
texture = new GuestDrawTexture(
descriptor.Address, descriptor.Address,
descriptor.Width, descriptor.Width,
descriptor.Height, descriptor.Height,
+172 -320
View File
@@ -3,6 +3,7 @@
using SharpEmu.HLE; using SharpEmu.HLE;
using SharpEmu.Libs.Kernel; using SharpEmu.Libs.Kernel;
using SharpEmu.Libs.Media;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using System.Globalization;
@@ -15,6 +16,10 @@ public static class AvPlayerExports
private const int InvalidParameters = unchecked((int)0x806A0001); private const int InvalidParameters = unchecked((int)0x806A0001);
private const int OperationFailed = unchecked((int)0x806A0002); private const int OperationFailed = unchecked((int)0x806A0002);
private const int FrameBufferCount = 3; private const int FrameBufferCount = 3;
private const int MaxCatchUpFrames = 2;
private const ulong TextureAllocationAlignment = 0x100;
private const int FramePitchAlignment = 64;
private const int FrameHeightAlignment = 16;
private const int FrameInfoSize = 40; private const int FrameInfoSize = 40;
private const int FrameInfoExSize = 104; private const int FrameInfoExSize = 104;
// This structure is 32 bytes. A larger write can damage the guest stack. // This structure is 32 bytes. A larger write can damage the guest stack.
@@ -22,6 +27,7 @@ public static class AvPlayerExports
private const int StreamInfoExSize = 32; private const int StreamInfoExSize = 32;
private const int MaxGuestPathLength = 4096; private const int MaxGuestPathLength = 4096;
private static readonly object StateGate = new(); private static readonly object StateGate = new();
private static readonly HashSet<string> TracedOnce = new();
private static readonly Dictionary<ulong, PlayerState> Players = new(); private static readonly Dictionary<ulong, PlayerState> Players = new();
private static int _traceCount; private static int _traceCount;
@@ -31,6 +37,7 @@ public static class AvPlayerExports
public bool AutoStart { get; init; } public bool AutoStart { get; init; }
public ulong AllocatorObject { get; init; } public ulong AllocatorObject { get; init; }
public ulong AllocateTextureCallback { get; init; } public ulong AllocateTextureCallback { get; init; }
public ulong AllocateCallback { get; init; }
public ulong EventObject { get; init; } public ulong EventObject { get; init; }
public ulong EventCallback { get; init; } public ulong EventCallback { get; init; }
public string? SourcePath { get; set; } public string? SourcePath { get; set; }
@@ -42,11 +49,10 @@ public static class AvPlayerExports
public bool Paused { get; set; } public bool Paused { get; set; }
public bool Looping { get; set; } public bool Looping { get; set; }
public bool EndOfStream { get; set; } public bool EndOfStream { get; set; }
public Process? Decoder { get; set; }
public Stream? DecoderOutput { get; set; } public Stream? DecoderOutput { get; set; }
public Process? AudioDecoder { get; set; }
public Stream? AudioDecoderOutput { get; set; } public Stream? AudioDecoderOutput { get; set; }
public Stopwatch PlaybackClock { get; } = new(); public Stopwatch PlaybackClock { get; } = new();
public long SkippedFrameDebt { get; set; }
public byte[]? RawFrame { get; set; } public byte[]? RawFrame { get; set; }
public byte[]? RawAudioFrame { get; set; } public byte[]? RawAudioFrame { get; set; }
public byte[]? PaddedFrame { get; set; } public byte[]? PaddedFrame { get; set; }
@@ -66,42 +72,6 @@ public static class AvPlayerExports
DecoderOutput = null; DecoderOutput = null;
AudioDecoderOutput?.Dispose(); AudioDecoderOutput?.Dispose();
AudioDecoderOutput = null; AudioDecoderOutput = null;
if (Decoder is not null)
{
try
{
if (!Decoder.HasExited)
{
Decoder.Kill(entireProcessTree: true);
}
}
catch (InvalidOperationException)
{
}
finally
{
Decoder.Dispose();
Decoder = null;
}
}
if (AudioDecoder is not null)
{
try
{
if (!AudioDecoder.HasExited)
{
AudioDecoder.Kill(entireProcessTree: true);
}
}
catch (InvalidOperationException)
{
}
finally
{
AudioDecoder.Dispose();
AudioDecoder = null;
}
}
} }
public void ResetPlayback() public void ResetPlayback()
@@ -110,6 +80,7 @@ public static class AvPlayerExports
PlaybackClock.Reset(); PlaybackClock.Reset();
NextFrameIndex = 0; NextFrameIndex = 0;
NextAudioFrameIndex = 0; NextAudioFrameIndex = 0;
SkippedFrameDebt = 0;
EndOfStream = false; EndOfStream = false;
} }
} }
@@ -137,6 +108,7 @@ public static class AvPlayerExports
AutoStart = TryReadByte(ctx, initDataAddress + 108, out var autoStart) && autoStart != 0, AutoStart = TryReadByte(ctx, initDataAddress + 108, out var autoStart) && autoStart != 0,
AllocatorObject = TryReadUInt64(ctx, initDataAddress, out var allocatorObject) ? allocatorObject : 0, AllocatorObject = TryReadUInt64(ctx, initDataAddress, out var allocatorObject) ? allocatorObject : 0,
AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 24, out var allocateTexture) ? allocateTexture : 0, AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 24, out var allocateTexture) ? allocateTexture : 0,
AllocateCallback = TryReadUInt64(ctx, initDataAddress + 8, out var allocate) ? allocate : 0,
EventObject = TryReadUInt64(ctx, initDataAddress + 80, out var eventObject) ? eventObject : 0, EventObject = TryReadUInt64(ctx, initDataAddress + 80, out var eventObject) ? eventObject : 0,
EventCallback = TryReadUInt64(ctx, initDataAddress + 88, out var eventCallback) ? eventCallback : 0, EventCallback = TryReadUInt64(ctx, initDataAddress + 88, out var eventCallback) ? eventCallback : 0,
}); });
@@ -191,6 +163,7 @@ public static class AvPlayerExports
AutoStart = TryReadByte(ctx, initDataAddress + 164, out var autoStart) && autoStart != 0, AutoStart = TryReadByte(ctx, initDataAddress + 164, out var autoStart) && autoStart != 0,
AllocatorObject = TryReadUInt64(ctx, initDataAddress + 8, out var allocatorObject) ? allocatorObject : 0, AllocatorObject = TryReadUInt64(ctx, initDataAddress + 8, out var allocatorObject) ? allocatorObject : 0,
AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 32, out var allocateTexture) ? allocateTexture : 0, AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 32, out var allocateTexture) ? allocateTexture : 0,
AllocateCallback = TryReadUInt64(ctx, initDataAddress + 16, out var allocate) ? allocate : 0,
EventObject = TryReadUInt64(ctx, initDataAddress + 88, out var eventObject) ? eventObject : 0, EventObject = TryReadUInt64(ctx, initDataAddress + 88, out var eventObject) ? eventObject : 0,
EventCallback = TryReadUInt64(ctx, initDataAddress + 96, out var eventCallback) ? eventCallback : 0, EventCallback = TryReadUInt64(ctx, initDataAddress + 96, out var eventCallback) ? eventCallback : 0,
}); });
@@ -356,7 +329,7 @@ public static class AvPlayerExports
} }
player.Paused = false; player.Paused = false;
if (player.Decoder is not null) if (player.DecoderOutput is not null)
{ {
player.PlaybackClock.Start(); player.PlaybackClock.Start();
} }
@@ -388,7 +361,13 @@ public static class AvPlayerExports
ExportName = "sceAvPlayerEnableStream", ExportName = "sceAvPlayerEnableStream",
Target = Generation.Gen4 | Generation.Gen5, Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAvPlayer")] LibraryName = "libSceAvPlayer")]
public static int AvPlayerEnableStream(CpuContext ctx) => ValidatePlayer(ctx); public static int AvPlayerEnableStream(CpuContext ctx)
{
TraceOnce(
$"enable_stream_{ctx[CpuRegister.Rsi]}",
$"enable_stream index={ctx[CpuRegister.Rsi]}");
return ValidatePlayer(ctx);
}
[SysAbiExport( [SysAbiExport(
Nid = "k-q+xOxdc3E", Nid = "k-q+xOxdc3E",
@@ -445,10 +424,13 @@ public static class AvPlayerExports
{ {
lock (StateGate) lock (StateGate)
{ {
return SetReturn( var found = Players.TryGetValue(ctx[CpuRegister.Rdi], out var player);
ctx, var active = found && player!.Started && !player.EndOfStream;
Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) && TraceOnce(
player.Started && !player.EndOfStream ? 1 : 0); "is_active",
$"is_active found={found} started={(found && player!.Started)} " +
$"eos={(found && player!.EndOfStream)} returned={(active ? 1 : 0)}");
return SetReturn(ctx, active ? 1 : 0);
} }
} }
@@ -476,13 +458,21 @@ public static class AvPlayerExports
var infoAddress = ctx[CpuRegister.Rsi]; var infoAddress = ctx[CpuRegister.Rsi];
lock (StateGate) lock (StateGate)
{ {
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) || var found = Players.TryGetValue(ctx[CpuRegister.Rdi], out var player);
infoAddress == 0 || !player.Started || player.Paused || player.EndOfStream || if (!found || infoAddress == 0 || !player!.Started || player.Paused ||
player.SourcePath is null || !EnsureAudioDecoder(player)) player.EndOfStream || player.SourcePath is null || !EnsureAudioDecoder(player))
{ {
TraceOnce(
"audio_data_refused",
$"audio_data refused found={found} info=0x{infoAddress:X16} " +
$"started={(found && player!.Started)} paused={(found && player!.Paused)} " +
$"eos={(found && player!.EndOfStream)} " +
$"decoder={(found && player!.SourcePath is not null && EnsureAudioDecoder(player))}");
return SetReturn(ctx, 0); return SetReturn(ctx, 0);
} }
TraceOnce("audio_data_ok", "audio_data first delivery");
const int samplesPerFrame = 1024; const int samplesPerFrame = 1024;
const int channelCount = 2; const int channelCount = 2;
const int sampleRate = 48_000; const int sampleRate = 48_000;
@@ -560,7 +550,9 @@ public static class AvPlayerExports
{ {
lock (StateGate) lock (StateGate)
{ {
return SetReturn(ctx, Players.ContainsKey(ctx[CpuRegister.Rdi]) ? 2 : InvalidParameters); var known = Players.ContainsKey(ctx[CpuRegister.Rdi]);
TraceOnce("stream_count", $"stream_count known={known} returned={(known ? 2 : -1)}");
return SetReturn(ctx, known ? 2 : InvalidParameters);
} }
} }
@@ -637,6 +629,10 @@ public static class AvPlayerExports
return SetReturn(ctx, InvalidParameters); return SetReturn(ctx, InvalidParameters);
} }
TraceOnce(
$"stream_info_{streamIndex}_{infoSize}",
$"stream_info index={streamIndex} size={infoSize} " +
$"type={(streamIndex == 0 ? "video" : "audio")} duration_ms={player.DurationMilliseconds}");
return SetReturn(ctx, 0); return SetReturn(ctx, 0);
} }
} }
@@ -672,6 +668,8 @@ public static class AvPlayerExports
} }
EnsureGuestVideoBuffers(ctx, player);
NotifyEvent(ctx, player, 2); // StateReady NotifyEvent(ctx, player, 2); // StateReady
if (autoStart) if (autoStart)
{ {
@@ -699,7 +697,20 @@ public static class AvPlayerExports
} }
var fps = Math.Max(1.0, player.FramesPerSecond); var fps = Math.Max(1.0, player.FramesPerSecond);
var expectedFrame = (long)Math.Floor(player.PlaybackClock.Elapsed.TotalSeconds * fps); var expectedFrame =
(long)Math.Floor(player.PlaybackClock.Elapsed.TotalSeconds * fps) -
player.SkippedFrameDebt;
var behind = expectedFrame - player.NextFrameIndex;
if (behind > MaxCatchUpFrames)
{
player.SkippedFrameDebt += behind - MaxCatchUpFrames;
expectedFrame = player.NextFrameIndex + MaxCatchUpFrames;
TraceOnce(
"catch_up_capped",
$"catch_up capped behind={behind} max={MaxCatchUpFrames} " +
$"fps={fps:F3} {player.Width}x{player.Height}");
}
while (player.NextFrameIndex < expectedFrame) while (player.NextFrameIndex < expectedFrame)
{ {
if (!ReadFrame(player)) if (!ReadFrame(player))
@@ -748,62 +759,28 @@ public static class AvPlayerExports
return true; return true;
} }
var ffmpeg = FindFfmpeg(); if (player.SourcePath is null)
if (ffmpeg is null || player.SourcePath is null)
{ {
Console.Error.WriteLine("[AVPLAYER][ERROR] FFmpeg was not found. Set SHARPEMU_FFMPEG_PATH.");
return false; return false;
} }
var startInfo = new ProcessStartInfo(ffmpeg) if (!FfmpegMediaStream.TryOpenVideo(
player.SourcePath,
checked((int)player.Width),
checked((int)player.Height),
out var videoStream) ||
videoStream is null)
{ {
UseShellExecute = false, Console.Error.WriteLine(
RedirectStandardOutput = true, $"[AVPLAYER][ERROR] Could not open a video stream in '{player.SourcePath}'.");
RedirectStandardError = true,
CreateNoWindow = true,
};
startInfo.ArgumentList.Add("-nostdin");
startInfo.ArgumentList.Add("-hide_banner");
startInfo.ArgumentList.Add("-loglevel");
startInfo.ArgumentList.Add("error");
startInfo.ArgumentList.Add("-i");
startInfo.ArgumentList.Add(player.SourcePath);
startInfo.ArgumentList.Add("-map");
startInfo.ArgumentList.Add("0:v:0");
startInfo.ArgumentList.Add("-an");
startInfo.ArgumentList.Add("-pix_fmt");
startInfo.ArgumentList.Add("nv12");
startInfo.ArgumentList.Add("-f");
startInfo.ArgumentList.Add("rawvideo");
startInfo.ArgumentList.Add("pipe:1");
try
{
player.Decoder = Process.Start(startInfo);
if (player.Decoder is null)
{
return false;
}
player.Decoder.ErrorDataReceived += (_, eventArgs) =>
{
if (!string.IsNullOrWhiteSpace(eventArgs.Data))
{
Console.Error.WriteLine($"[AVPLAYER][FFMPEG] {eventArgs.Data}");
}
};
player.Decoder.BeginErrorReadLine();
player.DecoderOutput = player.Decoder.StandardOutput.BaseStream;
player.RawFrame = new byte[checked(player.Width * player.Height * 3 / 2)];
player.PlaybackClock.Start();
Trace($"decoder_started pid={player.Decoder.Id} source='{player.SourcePath}'");
return true;
}
catch (Exception exception) when (exception is IOException or InvalidOperationException or System.ComponentModel.Win32Exception)
{
Console.Error.WriteLine($"[AVPLAYER][ERROR] Failed to launch FFmpeg: {exception.Message}");
player.Dispose();
return false; return false;
} }
player.DecoderOutput = videoStream;
player.RawFrame = new byte[checked(player.Width * player.Height * 3 / 2)];
player.PlaybackClock.Start();
Trace($"decoder_started source='{player.SourcePath}' {player.Width}x{player.Height} nv12");
return true;
} }
private static bool EnsureAudioDecoder(PlayerState player) private static bool EnsureAudioDecoder(PlayerState player)
@@ -813,65 +790,21 @@ public static class AvPlayerExports
return true; return true;
} }
var ffmpeg = FindFfmpeg(); if (player.SourcePath is null)
if (ffmpeg is null || player.SourcePath is null)
{ {
return false; return false;
} }
var startInfo = new ProcessStartInfo(ffmpeg) if (!FfmpegMediaStream.TryOpenAudio(player.SourcePath, out var audioStream) ||
audioStream is null)
{ {
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
startInfo.ArgumentList.Add("-nostdin");
startInfo.ArgumentList.Add("-hide_banner");
startInfo.ArgumentList.Add("-loglevel");
startInfo.ArgumentList.Add("error");
startInfo.ArgumentList.Add("-i");
startInfo.ArgumentList.Add(player.SourcePath);
startInfo.ArgumentList.Add("-map");
startInfo.ArgumentList.Add("0:a:0");
startInfo.ArgumentList.Add("-vn");
startInfo.ArgumentList.Add("-ac");
startInfo.ArgumentList.Add("2");
startInfo.ArgumentList.Add("-ar");
startInfo.ArgumentList.Add("48000");
startInfo.ArgumentList.Add("-f");
startInfo.ArgumentList.Add("s16le");
startInfo.ArgumentList.Add("pipe:1");
try
{
player.AudioDecoder = Process.Start(startInfo);
if (player.AudioDecoder is null)
{
return false;
}
player.AudioDecoder.ErrorDataReceived += (_, eventArgs) =>
{
if (!string.IsNullOrWhiteSpace(eventArgs.Data))
{
Console.Error.WriteLine($"[AVPLAYER][FFMPEG-AUDIO] {eventArgs.Data}");
}
};
player.AudioDecoder.BeginErrorReadLine();
player.AudioDecoderOutput = player.AudioDecoder.StandardOutput.BaseStream;
player.RawAudioFrame = new byte[1024 * 2 * sizeof(short)];
Trace($"audio_decoder_started pid={player.AudioDecoder.Id} source='{player.SourcePath}'");
return true;
}
catch (Exception exception) when (exception is IOException or InvalidOperationException or System.ComponentModel.Win32Exception)
{
Console.Error.WriteLine($"[AVPLAYER][ERROR] Failed to launch FFmpeg audio decoder: {exception.Message}");
player.AudioDecoderOutput?.Dispose();
player.AudioDecoderOutput = null;
player.AudioDecoder?.Dispose();
player.AudioDecoder = null;
return false; return false;
} }
player.AudioDecoderOutput = audioStream;
player.RawAudioFrame = new byte[1024 * FfmpegMediaStream.AudioChannels * sizeof(short)];
Trace($"audio_decoder_started source='{player.SourcePath}' s16 stereo 48000");
return true;
} }
private static bool ReadFrame(PlayerState player) private static bool ReadFrame(PlayerState player)
@@ -923,9 +856,9 @@ public static class AvPlayerExports
return false; return false;
} }
var alignedWidth = AlignUp(player.Width, 16); var alignedWidth = AlignUp(player.Width, FramePitchAlignment);
var alignedHeight = AlignUp(player.Height, 16); var alignedHeight = AlignUp(player.Height, FrameHeightAlignment);
var bufferStride = checked(alignedWidth * alignedHeight * 3 / 2); var bufferStride = GetVideoBufferSize(player);
if (player.GuestBuffers[0] == 0) if (player.GuestBuffers[0] == 0)
{ {
if (!AllocateGuestVideoBuffers(ctx, player, bufferStride)) if (!AllocateGuestVideoBuffers(ctx, player, bufferStride))
@@ -981,39 +914,78 @@ public static class AvPlayerExports
return ctx.Memory.TryWrite(infoAddress, info); return ctx.Memory.TryWrite(infoAddress, info);
} }
private static int GetVideoBufferSize(PlayerState player) =>
checked(
AlignUp(player.Width, FramePitchAlignment) *
AlignUp(player.Height, FrameHeightAlignment) * 3 / 2);
private static void EnsureGuestVideoBuffers(CpuContext ctx, PlayerState player)
{
lock (StateGate)
{
if (player.GuestBuffers[0] != 0 || player.Width <= 0 || player.Height <= 0)
{
return;
}
var bufferSize = GetVideoBufferSize(player);
if (AllocateGuestVideoBuffers(ctx, player, bufferSize))
{
player.GuestBufferStride = bufferSize;
}
}
}
private static bool AllocateGuestVideoBuffers(CpuContext ctx, PlayerState player, int bufferSize) private static bool AllocateGuestVideoBuffers(CpuContext ctx, PlayerState player, int bufferSize)
{ {
var scheduler = GuestThreadExecution.Scheduler; var scheduler = GuestThreadExecution.Scheduler;
if (!player.TextureAllocatorFailed && player.AllocateTextureCallback != 0 && scheduler is not null) if (!player.TextureAllocatorFailed && scheduler is not null)
{ {
for (var index = 0; index < player.GuestBuffers.Length; index++) foreach (var (callback, kind) in new[]
{
(player.AllocateTextureCallback, "texture"),
(player.AllocateCallback, "generic"),
})
{ {
if (!scheduler.TryCallGuestFunction( if (callback == 0)
ctx,
player.AllocateTextureCallback,
player.AllocatorObject,
0x100,
checked((ulong)bufferSize),
0,
0,
"avplayer_allocate_texture",
out var buffer,
out var error) || buffer == 0)
{ {
Console.Error.WriteLine( continue;
$"[AVPLAYER][ERROR] Guest texture allocation failed index={index} " + }
$"callback=0x{player.AllocateTextureCallback:X16}: {error ?? "returned null"}");
player.TextureAllocatorFailed = true; var allocated = true;
Array.Clear(player.GuestBuffers); for (var index = 0; index < player.GuestBuffers.Length; index++)
break; {
if (!scheduler.TryCallGuestFunction(
ctx,
callback,
player.AllocatorObject,
TextureAllocationAlignment,
checked((ulong)bufferSize),
0,
0,
"avplayer_allocate_" + kind,
out var buffer,
out var error) || buffer == 0)
{
Console.Error.WriteLine(
$"[AVPLAYER][WARN] Guest {kind} allocation failed index={index} " +
$"callback=0x{callback:X16} size={bufferSize} " +
$"align=0x{TextureAllocationAlignment:X}: {error ?? "returned null"}");
allocated = false;
Array.Clear(player.GuestBuffers);
break;
}
player.GuestBuffers[index] = buffer;
Trace($"{kind}_buffer index={index} data=0x{buffer:X16} size={bufferSize}");
}
if (allocated)
{
return true;
} }
player.GuestBuffers[index] = buffer;
Trace($"texture_buffer index={index} data=0x{buffer:X16} size={bufferSize}");
}
if (!player.TextureAllocatorFailed)
{
return true;
} }
player.TextureAllocatorFailed = true;
} }
if (!KernelMemoryCompatExports.TryAllocateHleData( if (!KernelMemoryCompatExports.TryAllocateHleData(
@@ -1043,158 +1015,25 @@ public static class AvPlayerExports
height = 0; height = 0;
framesPerSecond = 30.0; framesPerSecond = 30.0;
durationMilliseconds = 0; durationMilliseconds = 0;
var ffmpeg = FindFfmpeg();
if (ffmpeg is null) if (!FfmpegMediaStream.TryProbe(path, out width, out height, out var rate, out var duration))
{
return false;
}
var ffprobe = GetFfprobePath(ffmpeg, OperatingSystem.IsWindows());
if (!File.Exists(ffprobe))
{ {
return false; return false;
} }
var startInfo = new ProcessStartInfo(ffprobe) if (rate > 0)
{ {
UseShellExecute = false, framesPerSecond = rate;
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
startInfo.ArgumentList.Add("-v");
startInfo.ArgumentList.Add("error");
startInfo.ArgumentList.Add("-select_streams");
startInfo.ArgumentList.Add("v:0");
startInfo.ArgumentList.Add("-show_entries");
startInfo.ArgumentList.Add("stream=width,height,avg_frame_rate,duration");
startInfo.ArgumentList.Add("-of");
startInfo.ArgumentList.Add("default=noprint_wrappers=1");
startInfo.ArgumentList.Add(path);
try
{
using var process = Process.Start(startInfo);
if (process is null)
{
return false;
}
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
Console.Error.WriteLine($"[AVPLAYER][FFPROBE] {error.Trim()}");
return false;
}
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var separator = line.IndexOf('=');
if (separator < 1)
{
continue;
}
var key = line[..separator];
var value = line[(separator + 1)..];
switch (key)
{
case "width":
_ = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out width);
break;
case "height":
_ = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out height);
break;
case "avg_frame_rate":
var parts = value.Split('/');
if (parts.Length == 2 &&
double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var numerator) &&
double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var denominator) &&
denominator != 0)
{
framesPerSecond = numerator / denominator;
}
break;
case "duration":
if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var duration))
{
durationMilliseconds = checked((ulong)Math.Max(0, Math.Round(duration * 1000.0)));
}
break;
}
}
return width > 0 && height > 0 && framesPerSecond > 0;
} }
catch (Exception exception) when (exception is IOException or InvalidOperationException or System.ComponentModel.Win32Exception)
if (duration > 0)
{ {
Console.Error.WriteLine($"[AVPLAYER][ERROR] Failed to probe video: {exception.Message}"); durationMilliseconds = checked((ulong)Math.Max(0, Math.Round(duration * 1000.0)));
return false;
} }
return width > 0 && height > 0 && framesPerSecond > 0;
} }
internal static string? FindFfmpeg() =>
FindFfmpeg(
Environment.GetEnvironmentVariable("SHARPEMU_FFMPEG_PATH"),
Environment.GetEnvironmentVariable("PATH"),
OperatingSystem.IsWindows(),
AppContext.BaseDirectory);
internal static string? FindFfmpeg(
string? configured,
string? searchPath,
bool isWindows,
string? baseDirectory = null)
{
if (!string.IsNullOrWhiteSpace(configured) && File.Exists(configured))
{
return configured;
}
var executable = isWindows ? "ffmpeg.exe" : "ffmpeg";
if (!string.IsNullOrWhiteSpace(baseDirectory))
{
foreach (var candidate in new[]
{
Path.Combine(baseDirectory, executable),
Path.Combine(baseDirectory, "ffmpeg", executable),
})
{
if (File.Exists(candidate))
{
return candidate;
}
}
}
foreach (var directory in (searchPath ?? string.Empty)
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
var candidate = Path.Combine(RemovePathQuotes(directory), executable);
if (File.Exists(candidate))
{
return candidate;
}
}
foreach (var candidate in new[] { "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg" })
{
if (File.Exists(candidate))
{
return candidate;
}
}
return null;
}
internal static string GetFfprobePath(string ffmpeg, bool isWindows) =>
Path.Combine(
Path.GetDirectoryName(ffmpeg) ?? string.Empty,
isWindows ? "ffprobe.exe" : "ffprobe");
private static string RemovePathQuotes(string directory) =>
directory.Length >= 2 && directory[0] == '"' && directory[^1] == '"'
? directory[1..^1]
: directory;
internal static string? ResolveGuestPath(string guestPath) internal static string? ResolveGuestPath(string guestPath)
{ {
if (string.IsNullOrWhiteSpace(guestPath)) if (string.IsNullOrWhiteSpace(guestPath))
@@ -1606,4 +1445,17 @@ public static class AvPlayerExports
Console.Error.WriteLine($"[AVPLAYER][INFO] {message}"); Console.Error.WriteLine($"[AVPLAYER][INFO] {message}");
} }
} }
private static void TraceOnce(string key, string message)
{
lock (TracedOnce)
{
if (!TracedOnce.Add(key))
{
return;
}
}
Console.Error.WriteLine($"[AVPLAYER][INFO] {message}");
}
} }
@@ -1,166 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Diagnostics;
using SharpEmu.Libs.AvPlayer;
namespace SharpEmu.Libs.Bink;
internal sealed class FfmpegBinkFrameSource : IBinkFrameDecoder
{
private readonly Process _process;
private readonly Stream _output;
private int _errorLines;
private int _disposed;
private FfmpegBinkFrameSource(
Process process,
uint width,
uint height,
uint framesPerSecondNumerator,
uint framesPerSecondDenominator)
{
_process = process;
_output = process.StandardOutput.BaseStream;
Width = width;
Height = height;
FramesPerSecondNumerator = framesPerSecondNumerator;
FramesPerSecondDenominator = framesPerSecondDenominator;
}
public uint Width { get; }
public uint Height { get; }
public uint FramesPerSecondNumerator { get; }
public uint FramesPerSecondDenominator { get; }
internal static bool IsAvailable => AvPlayerExports.FindFfmpeg() is not null;
internal static bool TryOpen(
string path,
uint width,
uint height,
uint framesPerSecondNumerator,
uint framesPerSecondDenominator,
out FfmpegBinkFrameSource? source)
{
source = null;
var ffmpeg = AvPlayerExports.FindFfmpeg();
if (ffmpeg is null)
{
return false;
}
var startInfo = new ProcessStartInfo(ffmpeg)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
startInfo.ArgumentList.Add("-nostdin");
startInfo.ArgumentList.Add("-hide_banner");
startInfo.ArgumentList.Add("-loglevel");
startInfo.ArgumentList.Add("error");
startInfo.ArgumentList.Add("-i");
startInfo.ArgumentList.Add(path);
startInfo.ArgumentList.Add("-map");
startInfo.ArgumentList.Add("0:v:0");
startInfo.ArgumentList.Add("-an");
startInfo.ArgumentList.Add("-pix_fmt");
startInfo.ArgumentList.Add("bgra");
startInfo.ArgumentList.Add("-f");
startInfo.ArgumentList.Add("rawvideo");
startInfo.ArgumentList.Add("pipe:1");
try
{
var process = Process.Start(startInfo);
if (process is null)
{
return false;
}
source = new FfmpegBinkFrameSource(
process,
width,
height,
framesPerSecondNumerator,
framesPerSecondDenominator);
process.ErrorDataReceived += source.OnErrorData;
process.BeginErrorReadLine();
return true;
}
catch (Exception exception) when (exception is IOException or
InvalidOperationException or
System.ComponentModel.Win32Exception)
{
Console.Error.WriteLine(
$"[LOADER][WARN] Bink FFmpeg decoder could not start: {exception.Message}");
return false;
}
}
public bool TryDecodeNextFrame(Span<byte> destination)
{
try
{
var offset = 0;
while (offset < destination.Length)
{
var read = _output.Read(destination[offset..]);
if (read == 0)
{
return false;
}
offset += read;
}
return true;
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException)
{
if (Volatile.Read(ref _disposed) == 0)
{
Console.Error.WriteLine(
$"[LOADER][WARN] Bink FFmpeg stream failed: {exception.Message}");
}
return false;
}
}
private void OnErrorData(object sender, DataReceivedEventArgs eventArgs)
{
if (string.IsNullOrWhiteSpace(eventArgs.Data) ||
Interlocked.Increment(ref _errorLines) > 20)
{
return;
}
Console.Error.WriteLine($"[LOADER][FFMPEG-BINK] {eventArgs.Data}");
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
_output.Dispose();
try
{
if (!_process.HasExited)
{
_process.Kill(entireProcessTree: true);
}
}
catch (InvalidOperationException)
{
}
finally
{
_process.Dispose();
}
}
}
+151
View File
@@ -8,7 +8,13 @@ namespace SharpEmu.Libs.Font;
public static class FontExports public static class FontExports
{ {
private const ushort GlyphMagic = 0x0F03;
private const int GlyphSize = 0x100;
private const int GlyphMetricsSize = 8 * sizeof(float);
private const int RenderOutputSize = 0x40;
private static readonly object AllocationGate = new(); private static readonly object AllocationGate = new();
private static readonly Stack<ulong> FreeGlyphs = new();
private static ulong _librarySelectionAddress; private static ulong _librarySelectionAddress;
private static ulong _rendererSelectionAddress; private static ulong _rendererSelectionAddress;
@@ -321,6 +327,151 @@ public static class FontExports
return SetSuccess(ctx); return SetSuccess(ctx);
} }
[SysAbiExport(
Nid = "C-4Qw5Srlyw",
ExportName = "sceFontGenerateCharGlyph",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int GenerateCharGlyph(CpuContext ctx)
{
var outputAddress = ctx[CpuRegister.Rcx];
if (outputAddress == 0)
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
}
if (!TryRentGlyph(ctx, out var glyph) ||
!ctx.TryWriteUInt64(outputAddress, glyph))
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
return SetSuccess(ctx);
}
[SysAbiExport(
Nid = "8-zmgsxkBek",
ExportName = "sceFontGlyphDefineAttribute",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int GlyphDefineAttribute(CpuContext ctx) => SetSuccess(ctx);
[SysAbiExport(
Nid = "LHDoRWVFGqk",
ExportName = "sceFontDeleteGlyph",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int DeleteGlyph(CpuContext ctx)
{
var glyphPointerAddress = ctx[CpuRegister.Rsi];
if (glyphPointerAddress == 0)
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
}
if (!ctx.TryReadUInt64(glyphPointerAddress, out var glyph))
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
if (glyph != 0)
{
lock (AllocationGate)
{
FreeGlyphs.Push(glyph);
}
}
return ctx.TryWriteUInt64(glyphPointerAddress, 0)
? SetSuccess(ctx)
: SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
[SysAbiExport(
Nid = "kAenWy1Zw5o",
ExportName = "sceFontRenderCharGlyphImageHorizontal",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int RenderCharGlyphImageHorizontal(CpuContext ctx)
{
var metricsAddress = ctx[CpuRegister.Rcx];
var resultAddress = ctx[CpuRegister.R8];
if (metricsAddress != 0)
{
var values = new[] { 8.0f, 16.0f, 0.0f, 12.0f, 8.0f, 0.0f, 0.0f, 16.0f };
for (var index = 0; index < values.Length; index++)
{
if (!TryWriteUInt32(
ctx,
metricsAddress + (ulong)(index * sizeof(float)),
BitConverter.SingleToUInt32Bits(values[index])))
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
}
}
if (resultAddress != 0)
{
Span<byte> cleared = stackalloc byte[RenderOutputSize];
cleared.Clear();
if (!ctx.Memory.TryWrite(resultAddress, cleared))
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
}
return SetSuccess(ctx);
}
[SysAbiExport(
Nid = "vzHs3C8lWJk",
ExportName = "sceFontCloseFont",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int CloseFont(CpuContext ctx) => SetSuccess(ctx);
[SysAbiExport(
Nid = "1QjhKxrsOB8",
ExportName = "sceFontUnbindRenderer",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int UnbindRenderer(CpuContext ctx) => SetSuccess(ctx);
[SysAbiExport(
Nid = "exAxkyVLt0s",
ExportName = "sceFontDestroyRenderer",
Target = Generation.Gen5,
LibraryName = "libSceFont")]
public static int DestroyRenderer(CpuContext ctx)
{
var rendererPointerAddress = ctx[CpuRegister.Rdi];
if (rendererPointerAddress == 0)
{
return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
}
return ctx.TryWriteUInt64(rendererPointerAddress, 0)
? SetSuccess(ctx)
: SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
private static bool TryRentGlyph(CpuContext ctx, out ulong glyph)
{
lock (AllocationGate)
{
if (FreeGlyphs.Count > 0)
{
glyph = FreeGlyphs.Pop();
return TryWriteUInt16(ctx, glyph, GlyphMagic);
}
}
return TryAllocateOpaque(ctx, GlyphSize, out glyph) &&
TryWriteUInt16(ctx, glyph, GlyphMagic);
}
private static int ReturnSelection(CpuContext ctx, ref ulong selectionAddress, uint objectSize) private static int ReturnSelection(CpuContext ctx, ref ulong selectionAddress, uint objectSize)
{ {
if (ctx[CpuRegister.Rdi] != 0) if (ctx[CpuRegister.Rdi] != 0)
+175
View File
@@ -0,0 +1,175 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.Buffers.Binary;
using System.Text;
using SharpEmu.HLE;
namespace SharpEmu.Libs.Ime;
public static class ImeDialogExports
{
private const int StatusNone = 0;
private const int StatusRunning = 1;
private const int StatusFinished = 2;
private const int EndStatusOk = 0;
private const ulong ParamMaxTextLengthOffset = 0x24;
private const ulong ParamInputTextBufferOffset = 0x28;
private const int ImeDialogErrorInvalidAddress = unchecked((int)0x80BC0001);
private const string DefaultInputText = "Sharp";
private static readonly object _gate = new();
private static int _status = StatusNone;
[SysAbiExport(
Nid = "NUeBrN7hzf0",
ExportName = "sceImeDialogInit",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceImeDialog")]
public static int ImeDialogInit(CpuContext ctx)
{
var parameterAddress = ctx[CpuRegister.Rdi];
if (parameterAddress == 0)
{
return SetReturn(ctx, ImeDialogErrorInvalidAddress);
}
TryWriteInputText(ctx, parameterAddress);
lock (_gate)
{
_status = StatusFinished;
}
return SetReturn(ctx, 0);
}
[SysAbiExport(
Nid = "IADmD4tScBY",
ExportName = "sceImeDialogGetStatus",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceImeDialog")]
public static int ImeDialogGetStatus(CpuContext ctx)
{
int status;
lock (_gate)
{
status = _status;
}
ctx[CpuRegister.Rax] = unchecked((ulong)(long)status);
return status;
}
[SysAbiExport(
Nid = "x01jxu+vxlc",
ExportName = "sceImeDialogGetResult",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceImeDialog")]
public static int ImeDialogGetResult(CpuContext ctx)
{
var resultAddress = ctx[CpuRegister.Rdi];
if (resultAddress == 0)
{
return SetReturn(ctx, ImeDialogErrorInvalidAddress);
}
Span<byte> result = stackalloc byte[8];
result.Clear();
BinaryPrimitives.WriteInt32LittleEndian(result, EndStatusOk);
ctx.Memory.TryWrite(resultAddress, result);
return SetReturn(ctx, 0);
}
[SysAbiExport(
Nid = "oBmw4xrmfKs",
ExportName = "sceImeDialogAbort",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceImeDialog")]
public static int ImeDialogAbort(CpuContext ctx)
{
lock (_gate)
{
_status = StatusFinished;
}
return SetReturn(ctx, 0);
}
[SysAbiExport(
Nid = "gyTyVn+bXMw",
ExportName = "sceImeDialogTerm",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceImeDialog")]
public static int ImeDialogTerm(CpuContext ctx)
{
lock (_gate)
{
_status = StatusNone;
}
return SetReturn(ctx, 0);
}
private static void TryWriteInputText(CpuContext ctx, ulong parameterAddress)
{
Span<byte> field = stackalloc byte[8];
if (!ctx.Memory.TryRead(parameterAddress + ParamInputTextBufferOffset, field))
{
return;
}
var bufferAddress = BinaryPrimitives.ReadUInt64LittleEndian(field);
if (bufferAddress == 0)
{
return;
}
var maxTextLength = 16u;
Span<byte> lengthField = stackalloc byte[4];
if (ctx.Memory.TryRead(parameterAddress + ParamMaxTextLengthOffset, lengthField))
{
var declared = BinaryPrimitives.ReadUInt32LittleEndian(lengthField);
if (declared is > 0 and <= 256)
{
maxTextLength = declared;
}
}
var text = Environment.GetEnvironmentVariable("SHARPEMU_DEFAULT_PROFILE");
if (string.IsNullOrEmpty(text))
{
text = DefaultInputText;
}
if ((uint)text.Length > maxTextLength)
{
text = text[..(int)maxTextLength];
}
var encoded = Encoding.Unicode.GetBytes(text);
Span<byte> payload = stackalloc byte[encoded.Length + 2];
encoded.CopyTo(payload);
payload[^2] = 0;
payload[^1] = 0;
if (ctx.Memory.TryWrite(bufferAddress, payload))
{
Console.Error.WriteLine(
$"[LOADER][WARN] ime.dialog_autofill buf=0x{bufferAddress:X16} " +
$"max={maxTextLength} text=\"{text}\"");
}
}
private static int SetReturn(CpuContext ctx, int result)
{
ctx[CpuRegister.Rax] = unchecked((ulong)(long)result);
return result;
}
}
@@ -3,7 +3,7 @@
using SharpEmu.HLE; using SharpEmu.HLE;
using SharpEmu.Libs.Ampr; using SharpEmu.Libs.Ampr;
using SharpEmu.Libs.Bink; using SharpEmu.Libs.Media;
using System.Buffers; using System.Buffers;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@@ -97,7 +97,7 @@ public static partial class KernelMemoryCompatExports
private static readonly object _fdGate = new(); private static readonly object _fdGate = new();
private static readonly Dictionary<int, FileStream> _openFiles = new(); private static readonly Dictionary<int, FileStream> _openFiles = new();
private static readonly Dictionary<int, Bink2MovieBridge.BinkGuestCompletionShim> private static readonly Dictionary<int, HostMovieBridge.BinkGuestCompletionShim>
_binkGuestCompletionShims = new(); _binkGuestCompletionShims = new();
private static readonly Dictionary<int, string> _observedBinkGuestFiles = new(); private static readonly Dictionary<int, string> _observedBinkGuestFiles = new();
private static readonly Dictionary<int, OpenDirectory> _openDirectories = new(); private static readonly Dictionary<int, OpenDirectory> _openDirectories = new();
@@ -1478,7 +1478,7 @@ public static partial class KernelMemoryCompatExports
} }
try try
{ {
if (Bink2MovieBridge.ShouldSkipGuestMovie(hostPath)) if (HostMovieBridge.ShouldSkipGuestMovie(hostPath))
{ {
LogOpenTrace( LogOpenTrace(
"_open bink-skip path='" + guestPath + "' host='" + hostPath + "_open bink-skip path='" + guestPath + "' host='" + hostPath +
@@ -1489,10 +1489,10 @@ public static partial class KernelMemoryCompatExports
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
} }
Bink2MovieBridge.BinkGuestCompletionShim binkCompletionShim = default; HostMovieBridge.BinkGuestCompletionShim binkCompletionShim = default;
var observedBinkMovie = false; var observedBinkMovie = false;
var useBinkCompletionShim = access == FileAccess.Read && var useBinkCompletionShim = access == FileAccess.Read &&
Bink2MovieBridge.TryTakeOverGuestMovie( HostMovieBridge.TryTakeOverGuestMovie(
hostPath, hostPath,
out binkCompletionShim, out binkCompletionShim,
out observedBinkMovie); out observedBinkMovie);
@@ -2227,7 +2227,7 @@ public static partial class KernelMemoryCompatExports
if (notifyBinkClose) if (notifyBinkClose)
{ {
Bink2MovieBridge.NotifyGuestMovieClosed(observedBinkPath!); HostMovieBridge.NotifyGuestMovieClosed(observedBinkPath!);
} }
stream.Dispose(); stream.Dispose();
ctx[CpuRegister.Rax] = 0; ctx[CpuRegister.Rax] = 0;
@@ -2256,7 +2256,7 @@ public static partial class KernelMemoryCompatExports
} }
FileStream? stream; FileStream? stream;
Bink2MovieBridge.BinkGuestCompletionShim completionShim = default; HostMovieBridge.BinkGuestCompletionShim completionShim = default;
var useBinkCompletionShim = false; var useBinkCompletionShim = false;
lock (_fdGate) lock (_fdGate)
{ {
@@ -2289,7 +2289,7 @@ public static partial class KernelMemoryCompatExports
// logic can't race ahead of what's still on screen. // logic can't race ahead of what's still on screen.
if (completionShim.Patch(positionBefore, buffer.AsSpan(0, read))) if (completionShim.Patch(positionBefore, buffer.AsSpan(0, read)))
{ {
Bink2MovieBridge.WaitForHostPlaybackToFinish(stream.Name); HostMovieBridge.WaitForHostPlaybackToFinish(stream.Name);
} }
} }
if (read > 0 && !ctx.Memory.TryWrite(bufferAddress, buffer.AsSpan(0, read))) if (read > 0 && !ctx.Memory.TryWrite(bufferAddress, buffer.AsSpan(0, read)))
@@ -0,0 +1,489 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.IO;
using System.Threading;
using FFmpeg.AutoGen;
namespace SharpEmu.Libs.Media;
internal sealed unsafe class FfmpegMediaStream : Stream
{
internal const int AudioSampleRate = 48000;
internal const int AudioChannels = 2;
private readonly object _decodeGate = new();
private readonly bool _isVideo;
private readonly int _videoWidth;
private readonly int _videoHeight;
private AVFormatContext* _formatContext;
private AVCodecContext* _codecContext;
private AVFrame* _frame;
private AVPacket* _packet;
private SwsContext* _swsContext;
private SwrContext* _swrContext;
private int _streamIndex;
private byte[] _pending = [];
private int _pendingOffset;
private bool _draining;
private bool _finished;
private int _disposed;
private FfmpegMediaStream(bool isVideo, int width, int height)
{
_isVideo = isVideo;
_videoWidth = width;
_videoHeight = height;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
internal static bool TryOpenVideo(
string path,
int width,
int height,
out FfmpegMediaStream? stream) =>
TryOpen(path, AVMediaType.AVMEDIA_TYPE_VIDEO, width, height, out stream);
internal static bool TryOpenAudio(string path, out FfmpegMediaStream? stream) =>
TryOpen(path, AVMediaType.AVMEDIA_TYPE_AUDIO, 0, 0, out stream);
private static bool TryOpen(
string path,
AVMediaType mediaType,
int width,
int height,
out FfmpegMediaStream? stream)
{
stream = null;
FfmpegRuntime.EnsureInitialized();
var candidate = new FfmpegMediaStream(mediaType == AVMediaType.AVMEDIA_TYPE_VIDEO, width, height);
AVFormatContext* formatContext = null;
try
{
if (ffmpeg.avformat_open_input(&formatContext, path, null, null) < 0)
{
return false;
}
if (ffmpeg.avformat_find_stream_info(formatContext, null) < 0)
{
ffmpeg.avformat_close_input(&formatContext);
return false;
}
AVCodec* decoder = null;
var streamIndex = ffmpeg.av_find_best_stream(formatContext, mediaType, -1, -1, &decoder, 0);
if (streamIndex < 0 || decoder is null)
{
ffmpeg.avformat_close_input(&formatContext);
return false;
}
var codecContext = ffmpeg.avcodec_alloc_context3(decoder);
if (codecContext is null ||
ffmpeg.avcodec_parameters_to_context(
codecContext,
formatContext->streams[streamIndex]->codecpar) < 0 ||
ffmpeg.avcodec_open2(codecContext, decoder, null) < 0)
{
if (codecContext is not null)
{
ffmpeg.avcodec_free_context(&codecContext);
}
ffmpeg.avformat_close_input(&formatContext);
return false;
}
candidate._formatContext = formatContext;
candidate._codecContext = codecContext;
candidate._streamIndex = streamIndex;
candidate._frame = ffmpeg.av_frame_alloc();
candidate._packet = ffmpeg.av_packet_alloc();
if (candidate._frame is null || candidate._packet is null)
{
candidate.Dispose();
return false;
}
stream = candidate;
return true;
}
catch (Exception exception)
{
Console.Error.WriteLine(
$"[AVPLAYER][ERROR] in-process decoder failed to open '{path}': {exception.Message}");
if (formatContext is not null)
{
ffmpeg.avformat_close_input(&formatContext);
}
candidate.Dispose();
return false;
}
}
internal static bool TryProbe(
string path,
out int width,
out int height,
out double frameRate,
out double durationSeconds)
{
width = 0;
height = 0;
frameRate = 0;
durationSeconds = 0;
FfmpegRuntime.EnsureInitialized();
AVFormatContext* formatContext = null;
try
{
if (ffmpeg.avformat_open_input(&formatContext, path, null, null) < 0)
{
return false;
}
if (ffmpeg.avformat_find_stream_info(formatContext, null) < 0)
{
return false;
}
var streamIndex = ffmpeg.av_find_best_stream(
formatContext, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, null, 0);
if (streamIndex < 0)
{
return false;
}
var stream = formatContext->streams[streamIndex];
width = stream->codecpar->width;
height = stream->codecpar->height;
var rate = stream->avg_frame_rate;
if (rate.den > 0 && rate.num > 0)
{
frameRate = (double)rate.num / rate.den;
}
if (stream->duration > 0 && stream->time_base.den > 0)
{
durationSeconds = stream->duration *
((double)stream->time_base.num / stream->time_base.den);
}
else if (formatContext->duration > 0)
{
durationSeconds = (double)formatContext->duration / ffmpeg.AV_TIME_BASE;
}
return width > 0 && height > 0;
}
finally
{
if (formatContext is not null)
{
ffmpeg.avformat_close_input(&formatContext);
}
}
}
public override int Read(byte[] buffer, int offset, int count) =>
Read(buffer.AsSpan(offset, count));
public override int Read(Span<byte> buffer)
{
if (buffer.IsEmpty)
{
return 0;
}
lock (_decodeGate)
{
if (Volatile.Read(ref _disposed) != 0)
{
return 0;
}
var written = 0;
while (written < buffer.Length)
{
if (_pendingOffset >= _pending.Length)
{
if (_finished || !TryDecodeIntoPending())
{
break;
}
continue;
}
var available = _pending.Length - _pendingOffset;
var take = Math.Min(available, buffer.Length - written);
_pending.AsSpan(_pendingOffset, take).CopyTo(buffer[written..]);
_pendingOffset += take;
written += take;
}
return written;
}
}
private bool TryDecodeIntoPending()
{
if (!TryReceiveFrame())
{
_finished = true;
return false;
}
var produced = _isVideo ? ConvertVideoFrame() : ConvertAudioFrame();
ffmpeg.av_frame_unref(_frame);
if (produced is null)
{
_finished = true;
return false;
}
_pending = produced;
_pendingOffset = 0;
return true;
}
private byte[]? ConvertVideoFrame()
{
var width = _videoWidth > 0 ? _videoWidth : _frame->width;
var height = _videoHeight > 0 ? _videoHeight : _frame->height;
if (width <= 0 || height <= 0)
{
return null;
}
_swsContext = ffmpeg.sws_getCachedContext(
_swsContext,
_frame->width,
_frame->height,
(AVPixelFormat)_frame->format,
width,
height,
AVPixelFormat.AV_PIX_FMT_NV12,
ffmpeg.SWS_FAST_BILINEAR,
null,
null,
null);
if (_swsContext is null)
{
return null;
}
var lumaBytes = width * height;
var output = new byte[lumaBytes + lumaBytes / 2];
fixed (byte* outputPointer = output)
{
var planes = new byte*[4] { outputPointer, outputPointer + lumaBytes, null, null };
var strides = new int[4] { width, width, 0, 0 };
var rows = ffmpeg.sws_scale(
_swsContext,
_frame->data,
_frame->linesize,
0,
_frame->height,
planes,
strides);
return rows == height ? output : null;
}
}
private byte[]? ConvertAudioFrame()
{
var outputLayout = new AVChannelLayout();
ffmpeg.av_channel_layout_default(&outputLayout, AudioChannels);
var inputLayout = _frame->ch_layout;
SwrContext* swrContext = _swrContext;
var configureResult = ffmpeg.swr_alloc_set_opts2(
&swrContext,
&outputLayout,
AVSampleFormat.AV_SAMPLE_FMT_S16,
AudioSampleRate,
&inputLayout,
(AVSampleFormat)_frame->format,
_frame->sample_rate,
0,
null);
_swrContext = swrContext;
if (configureResult < 0 || _swrContext is null)
{
return null;
}
if (ffmpeg.swr_is_initialized(_swrContext) == 0 && ffmpeg.swr_init(_swrContext) < 0)
{
return null;
}
var maxSamples = (int)ffmpeg.av_rescale_rnd(
ffmpeg.swr_get_delay(_swrContext, _frame->sample_rate) + _frame->nb_samples,
AudioSampleRate,
_frame->sample_rate,
AVRounding.AV_ROUND_UP);
if (maxSamples <= 0)
{
return null;
}
var output = new byte[maxSamples * AudioChannels * sizeof(short)];
fixed (byte* outputPointer = output)
{
var planes = stackalloc byte*[1];
planes[0] = outputPointer;
var converted = ffmpeg.swr_convert(
_swrContext,
planes,
maxSamples,
_frame->extended_data,
_frame->nb_samples);
if (converted < 0)
{
return null;
}
var byteCount = converted * AudioChannels * sizeof(short);
if (byteCount == output.Length)
{
return output;
}
var trimmed = new byte[byteCount];
output.AsSpan(0, byteCount).CopyTo(trimmed);
return trimmed;
}
}
private bool TryReceiveFrame()
{
while (true)
{
var receiveResult = ffmpeg.avcodec_receive_frame(_codecContext, _frame);
if (receiveResult >= 0)
{
return true;
}
if (receiveResult == ffmpeg.AVERROR_EOF ||
receiveResult != ffmpeg.AVERROR(ffmpeg.EAGAIN) ||
_draining)
{
return false;
}
if (!TryFeedPacket())
{
return false;
}
}
}
private bool TryFeedPacket()
{
while (true)
{
var readResult = ffmpeg.av_read_frame(_formatContext, _packet);
if (readResult < 0)
{
_draining = true;
return ffmpeg.avcodec_send_packet(_codecContext, null) >= 0;
}
if (_packet->stream_index != _streamIndex)
{
ffmpeg.av_packet_unref(_packet);
continue;
}
var sendResult = ffmpeg.avcodec_send_packet(_codecContext, _packet);
ffmpeg.av_packet_unref(_packet);
return sendResult >= 0;
}
}
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) =>
throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
base.Dispose(disposing);
return;
}
lock (_decodeGate)
{
if (_swsContext is not null)
{
ffmpeg.sws_freeContext(_swsContext);
_swsContext = null;
}
if (_swrContext is not null)
{
var swrContext = _swrContext;
ffmpeg.swr_free(&swrContext);
_swrContext = null;
}
if (_frame is not null)
{
var frame = _frame;
ffmpeg.av_frame_free(&frame);
_frame = null;
}
if (_packet is not null)
{
var packet = _packet;
ffmpeg.av_packet_free(&packet);
_packet = null;
}
if (_codecContext is not null)
{
var codecContext = _codecContext;
ffmpeg.avcodec_free_context(&codecContext);
_codecContext = null;
}
if (_formatContext is not null)
{
var formatContext = _formatContext;
ffmpeg.avformat_close_input(&formatContext);
_formatContext = null;
}
}
base.Dispose(disposing);
}
}
+32
View File
@@ -0,0 +1,32 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.IO;
using FFmpeg.AutoGen;
namespace SharpEmu.Libs.Media;
internal static class FfmpegRuntime
{
private static readonly object _gate = new();
private static bool _initialized;
internal static void EnsureInitialized()
{
if (_initialized)
{
return;
}
lock (_gate)
{
if (_initialized)
{
return;
}
_initialized = true;
ffmpeg.RootPath = Path.Combine(AppContext.BaseDirectory, "plugins");
DynamicallyLoadedBindings.Initialize();
}
}
}
@@ -5,7 +5,7 @@ using System.Buffers;
using FFmpeg.AutoGen; using FFmpeg.AutoGen;
using SharpEmu.HLE.Host; using SharpEmu.HLE.Host;
namespace SharpEmu.Libs.Bink; namespace SharpEmu.Libs.Media;
/// <summary> /// <summary>
/// Decodes a .bk2 (or any FFmpeg-readable movie) directly via FFmpeg's C API /// Decodes a .bk2 (or any FFmpeg-readable movie) directly via FFmpeg's C API
@@ -13,7 +13,7 @@ namespace SharpEmu.Libs.Bink;
/// libraries published by github.com/sharpemu/ffmpeg-core -- no native C /// libraries published by github.com/sharpemu/ffmpeg-core -- no native C
/// bridge of our own to build. See docs/bink2-bridge.md. /// bridge of our own to build. See docs/bink2-bridge.md.
/// </summary> /// </summary>
internal sealed unsafe class FfmpegNativeBinkFrameSource : IBinkFrameDecoder internal sealed unsafe class FfmpegVideoDecoder : IMediaFrameDecoder
{ {
private const int OutputAudioChannels = 2; private const int OutputAudioChannels = 2;
private const int OutputAudioBytesPerSample = sizeof(short); private const int OutputAudioBytesPerSample = sizeof(short);
@@ -48,7 +48,7 @@ internal sealed unsafe class FfmpegNativeBinkFrameSource : IBinkFrameDecoder
public uint FramesPerSecondDenominator { get; } public uint FramesPerSecondDenominator { get; }
private FfmpegNativeBinkFrameSource( private FfmpegVideoDecoder(
AVFormatContext* formatContext, AVFormatContext* formatContext,
AVCodecContext* codecContext, AVCodecContext* codecContext,
int videoStreamIndex, int videoStreamIndex,
@@ -77,43 +77,14 @@ internal sealed unsafe class FfmpegNativeBinkFrameSource : IBinkFrameDecoder
_packet = ffmpeg.av_packet_alloc(); _packet = ffmpeg.av_packet_alloc();
} }
private static bool _rootPathInitialized; private static void EnsureRootPathInitialized() =>
SharpEmu.Libs.Media.FfmpegRuntime.EnsureInitialized();
/// <summary>
/// Points FFmpeg.AutoGen at the FFmpeg shared libraries SharpEmu.CLI
/// downloads next to the executable (see SharpEmu.CLI.csproj's
/// FetchFfmpegRuntime target); kept as loose files rather than embedded
/// in the single-file bundle so the OS loader can resolve the normal
/// inter-library dependencies (avcodec depends on avutil, etc.) itself.
/// </summary>
private static void EnsureRootPathInitialized()
{
if (_rootPathInitialized)
{
return;
}
_rootPathInitialized = true;
// SharpEmu.CLI.csproj publishes FFmpeg's shared libraries into a
// "plugins" subfolder next to the executable rather than flat beside
// it (see NativeLibraryFolderName in SharpEmu.CLI.csproj).
ffmpeg.RootPath = Path.Combine(AppContext.BaseDirectory, "plugins");
// ffmpeg's static constructor runs DynamicallyLoadedBindings.Initialize()
// itself, but that constructor fires on first touch of the ffmpeg type --
// which is the RootPath assignment above -- so it binds against the
// default (empty) RootPath before the assignment's own setter body runs.
// Every function resolved during that first pass permanently throws
// NotSupportedException. Re-running Initialize() now, with RootPath
// actually set, rebinds everything against the real search path.
DynamicallyLoadedBindings.Initialize();
}
internal static bool TryOpen( internal static bool TryOpen(
string path, string path,
uint maximumWidth, uint maximumWidth,
uint maximumHeight, uint maximumHeight,
out FfmpegNativeBinkFrameSource? source) out FfmpegVideoDecoder? source)
{ {
source = null; source = null;
EnsureRootPathInitialized(); EnsureRootPathInitialized();
@@ -222,7 +193,7 @@ internal sealed unsafe class FfmpegNativeBinkFrameSource : IBinkFrameDecoder
outputHeight = Math.Max(1, outputHeight); outputHeight = Math.Max(1, outputHeight);
} }
source = new FfmpegNativeBinkFrameSource( source = new FfmpegVideoDecoder(
formatContext, formatContext,
codecContext, codecContext,
videoStreamIndex, videoStreamIndex,
@@ -4,29 +4,44 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Buffers.Binary; using System.Buffers.Binary;
namespace SharpEmu.Libs.Bink; namespace SharpEmu.Libs.Media;
/// <summary> /// <summary>
/// Optional host-side Bink 2 bridge for games that ship a static Bink player. /// Host-side movie bridge for games that decode video inside their own
/// executable instead of going through an HLE decoder.
/// ///
/// The game in that case never imports libSceVideodec, so an HLE video-decoder /// Such a game never imports libSceVideodec or sceAvPlayer, so no HLE export
/// export cannot see its movie frames. Kernel file opens identify the active /// can see its movie frames. Kernel file opens identify the active movie and
/// .bk2 file and the presenter requests BGRA frames from a tiny native adapter. /// the presenter requests BGRA frames from <see cref="FfmpegVideoDecoder"/> —
/// The adapter is deliberately a separate, user-supplied library: Bink 2 is a /// the same decoder sceAvPlayer uses, so every format is handled in one place.
/// proprietary SDK and SharpEmu must neither bundle it nor depend on its ABI.
/// </summary> /// </summary>
internal static class Bink2MovieBridge internal static class HostMovieBridge
{ {
private const uint MaxDimension = 16384; private const uint MaxDimension = 16384;
private const uint MaxHostVideoWidth = 1920; private const uint MaxHostVideoWidth = 1920;
private const uint MaxHostVideoHeight = 1080; private const uint MaxHostVideoHeight = 1080;
private static readonly string[] SelfDecodedMovieExtensions = [".bk2"];
private static bool IsSelfDecodedMovie(string hostPath)
{
foreach (var extension in SelfDecodedMovieExtensions)
{
if (hostPath.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private static readonly object Gate = new(); private static readonly object Gate = new();
private static string? _activePath; private static string? _activePath;
private static Bink2MovieInfo _activeInfo; private static Bink2MovieInfo _activeInfo;
private static byte[]? _frameBuffer; private static byte[]? _frameBuffer;
private static bool _frameBufferPresented; private static bool _frameBufferPresented;
private static BinkFramePlayback? _playback; private static MediaFramePlayback? _playback;
private static long _frameSerial; private static long _frameSerial;
private static uint _presentationWidth = MaxHostVideoWidth; private static uint _presentationWidth = MaxHostVideoWidth;
private static uint _presentationHeight = MaxHostVideoHeight; private static uint _presentationHeight = MaxHostVideoHeight;
@@ -62,7 +77,7 @@ internal static class Bink2MovieBridge
/// statically linked into its executable. /// statically linked into its executable.
/// </summary> /// </summary>
internal static bool ShouldSkipGuestMovie(string hostPath) => internal static bool ShouldSkipGuestMovie(string hostPath) =>
hostPath.EndsWith(".bk2", StringComparison.OrdinalIgnoreCase) && IsSelfDecodedMovie(hostPath) &&
ResolveMode() == MovieMode.Skip; ResolveMode() == MovieMode.Skip;
/// <summary> /// <summary>
@@ -71,8 +86,7 @@ internal static class Bink2MovieBridge
/// </summary> /// </summary>
internal static bool ObserveGuestMovie(string hostPath) internal static bool ObserveGuestMovie(string hostPath)
{ {
if (!hostPath.EndsWith(".bk2", StringComparison.OrdinalIgnoreCase) || if (!IsSelfDecodedMovie(hostPath) || !File.Exists(hostPath))
!File.Exists(hostPath))
{ {
return false; return false;
} }
@@ -186,9 +200,6 @@ internal static class Bink2MovieBridge
case MovieMode.Dummy: case MovieMode.Dummy:
AttachDummyMovieLocked(hostPath); AttachDummyMovieLocked(hostPath);
return; return;
case MovieMode.Ffmpeg:
AttachFfmpegMovieLocked(hostPath);
return;
case MovieMode.Native: case MovieMode.Native:
AttachNativeMovieLocked(hostPath); AttachNativeMovieLocked(hostPath);
return; return;
@@ -197,7 +208,7 @@ internal static class Bink2MovieBridge
private static void AttachNativeMovieLocked(string hostPath) private static void AttachNativeMovieLocked(string hostPath)
{ {
if (!FfmpegNativeBinkFrameSource.TryOpen( if (!FfmpegVideoDecoder.TryOpen(
hostPath, _presentationWidth, _presentationHeight, out var source) || hostPath, _presentationWidth, _presentationHeight, out var source) ||
source is null) source is null)
{ {
@@ -250,14 +261,13 @@ internal static class Bink2MovieBridge
if (string.Equals(configured, "ffmpeg", StringComparison.OrdinalIgnoreCase)) if (string.Equals(configured, "ffmpeg", StringComparison.OrdinalIgnoreCase))
{ {
return MovieMode.Ffmpeg; return MovieMode.Native;
} }
// Native is the default: FfmpegNativeBinkFrameSource.TryOpen degrades // Native is the default: FfmpegVideoDecoder.TryOpen degrades gracefully
// gracefully (falls back to the guest's own decode, logging one // (falls back to the guest's own decode, logging one informational line)
// informational line) if the FFmpeg libraries SharpEmu.CLI.csproj // if the FFmpeg libraries SharpEmu.CLI.csproj downloads next to the
// downloads next to the executable are genuinely unavailable, so // executable are genuinely unavailable, so defaulting to it is safe.
// defaulting to Native unconditionally is safe.
return MovieMode.Native; return MovieMode.Native;
} }
@@ -282,43 +292,15 @@ internal static class Bink2MovieBridge
info.Width + "x" + info.Height + "."); info.Width + "x" + info.Height + ".");
} }
private static void AttachFfmpegMovieLocked(string hostPath)
{
if (!TryReadBinkInfo(hostPath, out var info) || !IsValid(info))
{
Console.Error.WriteLine(
"[LOADER][WARN] Bink FFmpeg source has an invalid header: " +
Path.GetFileName(hostPath));
return;
}
if (!FfmpegBinkFrameSource.TryOpen(
hostPath,
info.Width,
info.Height,
info.FramesPerSecondNumerator,
info.FramesPerSecondDenominator,
out var source) || source is null)
{
return;
}
AttachPlaybackLocked(hostPath, info, source);
Console.Error.WriteLine(
"[LOADER][INFO] Bink FFmpeg source attached: " +
Path.GetFileName(hostPath) + " " + info.Width + "x" + info.Height + " @ " +
info.FramesPerSecondNumerator + "/" + info.FramesPerSecondDenominator + " fps.");
}
private static void AttachPlaybackLocked( private static void AttachPlaybackLocked(
string hostPath, string hostPath,
Bink2MovieInfo info, Bink2MovieInfo info,
IBinkFrameDecoder decoder) IMediaFrameDecoder decoder)
{ {
CloseActiveLocked(); CloseActiveLocked();
_activePath = hostPath; _activePath = hostPath;
_activeInfo = info; _activeInfo = info;
_playback = new BinkFramePlayback(decoder); _playback = new MediaFramePlayback(decoder);
} }
internal static bool TryReadBinkInfo(string path, out Bink2MovieInfo info) internal static bool TryReadBinkInfo(string path, out Bink2MovieInfo info)
@@ -406,7 +388,6 @@ internal static class Bink2MovieBridge
Skip, Skip,
Dummy, Dummy,
Native, Native,
Ffmpeg,
} }
private static readonly Queue<string> PendingMoviePaths = new(); private static readonly Queue<string> PendingMoviePaths = new();
@@ -4,9 +4,9 @@
using System.Diagnostics; using System.Diagnostics;
using SharpEmu.HLE.Host; using SharpEmu.HLE.Host;
namespace SharpEmu.Libs.Bink; namespace SharpEmu.Libs.Media;
internal interface IBinkFrameDecoder : IDisposable internal interface IMediaFrameDecoder : IDisposable
{ {
uint Width { get; } uint Width { get; }
@@ -23,12 +23,12 @@ internal interface IBinkFrameDecoder : IDisposable
/// Keeps blocking codec work away from the Vulkan presentation thread and /// Keeps blocking codec work away from the Vulkan presentation thread and
/// releases decoded frames according to the movie time base. /// releases decoded frames according to the movie time base.
/// </summary> /// </summary>
internal sealed class BinkFramePlayback : IDisposable internal sealed class MediaFramePlayback : IDisposable
{ {
private const int BufferCount = 5; private const int BufferCount = 5;
private readonly object _gate = new(); private readonly object _gate = new();
private readonly IBinkFrameDecoder _decoder; private readonly IMediaFrameDecoder _decoder;
private readonly Queue<byte[]> _freeBuffers = new(); private readonly Queue<byte[]> _freeBuffers = new();
private readonly Queue<DecodedFrame> _decodedFrames = new(); private readonly Queue<DecodedFrame> _decodedFrames = new();
private readonly Thread _decoderThread; private readonly Thread _decoderThread;
@@ -45,7 +45,7 @@ internal sealed class BinkFramePlayback : IDisposable
private bool _finished; private bool _finished;
private int _disposed; private int _disposed;
internal BinkFramePlayback(IBinkFrameDecoder decoder) internal MediaFramePlayback(IMediaFrameDecoder decoder)
{ {
_decoder = decoder; _decoder = decoder;
Width = decoder.Width; Width = decoder.Width;
@@ -33,12 +33,17 @@ public static class SaveDataDialogExports
LibraryName = "libSceSaveDataDialog")] LibraryName = "libSceSaveDataDialog")]
public static int SaveDataDialogInitialize(CpuContext ctx) public static int SaveDataDialogInitialize(CpuContext ctx)
{ {
if (Interlocked.CompareExchange(ref _status, StatusInitialized, StatusNone) != StatusNone) var previous = Interlocked.CompareExchange(
ref _status,
StatusInitialized,
StatusNone);
if (previous == StatusNone || previous == StatusFinished)
{ {
return ctx.SetReturn(ErrorAlreadyInitialized); Interlocked.Exchange(ref _status, StatusInitialized);
return ctx.SetReturn(ErrorOk);
} }
return ctx.SetReturn(ErrorOk); return ctx.SetReturn(ErrorAlreadyInitialized);
} }
[SysAbiExport( [SysAbiExport(
@@ -5,7 +5,7 @@ using Silk.NET.Core;
using Silk.NET.Core.Native; using Silk.NET.Core.Native;
using SharpEmu.HLE; using SharpEmu.HLE;
using SharpEmu.Libs.Agc; using SharpEmu.Libs.Agc;
using SharpEmu.Libs.Bink; using SharpEmu.Libs.Media;
using SharpEmu.Libs.Gpu; using SharpEmu.Libs.Gpu;
using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Vulkan; using SharpEmu.ShaderCompiler.Vulkan;
@@ -1046,14 +1046,50 @@ internal static unsafe class VulkanVideoPresenter
targets.Count > 8 || targets.Count > 8 ||
AnyRenderTargetInvalid(targets)) AnyRenderTargetInvalid(targets))
{ {
var dropCount = Interlocked.Increment(ref _offscreenDropTraceCount);
if (dropCount <= 16 || dropCount % 500 == 0)
{
var detail = targets.Count == 0
? "<no targets>"
: string.Join(
" ",
targets.Select(t => $"0x{t.Address:X}:{t.Width}x{t.Height}"));
Console.Error.WriteLine(
$"[LOADER][WARN] vk.offscreen_drop#{dropCount} spirv={pixelSpirv.Length} " +
$"mrt={targets.Count} vs=0x{shaderAddress:X16} {detail}");
}
return; return;
} }
var firstTarget = targets[0]; var firstTarget = targets[0];
if (RenderTargetsMismatchedOrAliased(targets, firstTarget)) if (RenderTargetsMismatchedOrAliased(targets, firstTarget))
{ {
Console.Error.WriteLine( var skipCount = Interlocked.Increment(ref _mrtSkipTraceCount);
"[LOADER][WARN] Vulkan skipped MRT draw with mismatched dimensions or aliased targets."); if (skipCount <= 16 || skipCount % 200 == 0)
{
var aliased = false;
for (var i = 0; i < targets.Count && !aliased; i++)
{
for (var j = i + 1; j < targets.Count; j++)
{
if (targets[i].Address == targets[j].Address)
{
aliased = true;
break;
}
}
}
var detail = string.Join(
" ",
targets.Select(t =>
$"0x{t.Address:X}:{t.Width}x{t.Height}:f{t.Format}/{t.NumberType}"));
Console.Error.WriteLine(
$"[LOADER][WARN] vk.mrt_skip#{skipCount} mrt={targets.Count} " +
$"aliased={aliased} vs=0x{shaderAddress:X16} {detail}");
}
return; return;
} }
@@ -1298,6 +1334,8 @@ internal static unsafe class VulkanVideoPresenter
} }
} }
private static long _mrtSkipTraceCount;
private static long _offscreenDropTraceCount;
private static long _perfDrawCount; private static long _perfDrawCount;
private static long _perfDrawTicks; private static long _perfDrawTicks;
private static long _perfPipelineCreations; private static long _perfPipelineCreations;
@@ -1834,8 +1872,22 @@ internal static unsafe class VulkanVideoPresenter
lock (_gate) lock (_gate)
{ {
return _availableGuestImages.TryGetValue(address, out var availableFormat) && if (!_availableGuestImages.TryGetValue(address, out var availableFormat))
availableFormat == guestFormat; {
return false;
}
if (availableFormat == guestFormat)
{
return true;
}
return TryDecodeRenderTargetFormat(
(availableFormat >> 8) & 0x1FFu,
availableFormat & 0xFFu,
out var resident) &&
TryDecodeRenderTargetFormat(format, numberType, out var requested) &&
Presenter.IsCompatibleViewFormat(resident.Format, requested.Format);
} }
} }
@@ -4452,7 +4504,7 @@ internal static unsafe class VulkanVideoPresenter
_swapchainFormat = surfaceFormat.Format; _swapchainFormat = surfaceFormat.Format;
_swapchainColorSpace = surfaceFormat.ColorSpace; _swapchainColorSpace = surfaceFormat.ColorSpace;
_extent = ChooseExtent(capabilities); _extent = ChooseExtent(capabilities);
Bink2MovieBridge.SetPresentationSize(_extent.Width, _extent.Height); HostMovieBridge.SetPresentationSize(_extent.Width, _extent.Height);
var presentMode = ChoosePresentMode(); var presentMode = ChoosePresentMode();
var imageCount = capabilities.MinImageCount + 1; var imageCount = capabilities.MinImageCount + 1;
if (capabilities.MaxImageCount != 0) if (capabilities.MaxImageCount != 0)
@@ -7675,7 +7727,7 @@ internal static unsafe class VulkanVideoPresenter
private void PumpHostMovieFrame() private void PumpHostMovieFrame()
{ {
if (!Bink2MovieBridge.TryDecodeNextFrame( if (!HostMovieBridge.TryDecodeNextFrame(
advanceClock: _hostMovieLumaTextureAddress != 0 && advanceClock: _hostMovieLumaTextureAddress != 0 &&
_hostMovieChromaTextureAddress != 0, _hostMovieChromaTextureAddress != 0,
out var pixels, out var pixels,
@@ -9219,6 +9271,27 @@ internal static unsafe class VulkanVideoPresenter
!_guestImages.ContainsKey(texture.Address)) !_guestImages.ContainsKey(texture.Address))
{ {
var guestFormat = GetGuestTextureFormat(texture.Format, texture.NumberType); var guestFormat = GetGuestTextureFormat(texture.Format, texture.NumberType);
var canonicalView = view;
if (texture.DstSelect != 0xFAC)
{
var identityViewInfo = new ImageViewCreateInfo
{
SType = StructureType.ImageViewCreateInfo,
Image = image,
ViewType = GetGuestTextureViewType(
texture.Type,
texture.ArrayedView),
Format = vkFormat,
Components = ToVkComponentMapping(0xFAC),
SubresourceRange = ColorSubresourceRange(layerCount: layers),
};
Check(
_vk.CreateImageView(_device, &identityViewInfo, null, out canonicalView),
"vkCreateImageView(texture identity)");
SetDebugName(ObjectType.ImageView, canonicalView.Handle, $"{debugName} identity view");
}
var guestImage = new GuestImageResource var guestImage = new GuestImageResource
{ {
Address = texture.Address, Address = texture.Address,
@@ -9234,7 +9307,7 @@ internal static unsafe class VulkanVideoPresenter
Format = vkFormat, Format = vkFormat,
Image = image, Image = image,
Memory = imageMemory, Memory = imageMemory,
View = view, View = canonicalView,
InitialUploadPending = true, InitialUploadPending = true,
IsCpuBacked = true, IsCpuBacked = true,
CpuContentFingerprint = contentFingerprint, CpuContentFingerprint = contentFingerprint,
@@ -11134,6 +11207,8 @@ internal static unsafe class VulkanVideoPresenter
EnsureGuestSubmissionCapacity(); EnsureGuestSubmissionCapacity();
resources = CreateComputeDispatchResources(work); resources = CreateComputeDispatchResources(work);
FlushBatchedGuestCommands();
var batchCount = Math.Max( var batchCount = Math.Max(
1u, 1u,
(uint)Math.Ceiling(work.GroupCountZ / (double)MaxComputeZSlicesPerSubmission)); (uint)Math.Ceiling(work.GroupCountZ / (double)MaxComputeZSlicesPerSubmission));
@@ -12075,6 +12150,7 @@ internal static unsafe class VulkanVideoPresenter
{ {
Console.Error.WriteLine( Console.Error.WriteLine(
$"[LOADER][WARN] Vulkan skipped storage render-target feedback loop " + $"[LOADER][WARN] Vulkan skipped storage render-target feedback loop " +
$"vs=0x{work.ShaderAddress:X16} " +
$"targets={string.Join(',', work.Targets.Where(target => target.Address != 0).Select(target => $"0x{target.Address:X16}"))}; " + $"targets={string.Join(',', work.Targets.Where(target => target.Address != 0).Select(target => $"0x{target.Address:X16}"))}; " +
"sampled aliases use ordered snapshots"); "sampled aliases use ordered snapshots");
ReturnPooledGuestData(work.Draw); ReturnPooledGuestData(work.Draw);
@@ -14285,11 +14361,6 @@ internal static unsafe class VulkanVideoPresenter
pendingGuestWork.Queue.Name, pendingGuestWork.Queue.Name,
StringComparison.Ordinal)) StringComparison.Ordinal))
{ {
// A host command buffer must never contain commands from
// two independent guest queues: an ordered action fences
// only its own queue's predecessor submissions.
// Keep the previous work label so a device-lost on this
// flush still names the draws that filled the batch.
FlushBatchedGuestCommands(); FlushBatchedGuestCommands();
} }
@@ -14329,14 +14400,7 @@ internal static unsafe class VulkanVideoPresenter
} }
try try
{ {
// A host-decoded movie only overrides which image gets
// presented (see the presentation selection below); the
// guest's own command stream keeps draining normally.
// Silently discarding these instead of executing them
// leaves guest-visible completion state (labels, buffers,
// job results) permanently unwritten, which desyncs the
// engine's own job system and previously crashed it
// shortly after the movie finished.
switch (work) switch (work)
{ {
case VulkanOffscreenGuestDraw offscreenDraw: case VulkanOffscreenGuestDraw offscreenDraw:
@@ -14658,6 +14722,8 @@ internal static unsafe class VulkanVideoPresenter
$"[LOADER][ERROR] Vulkan VideoOut translated draw setup failed: {exception.Message}"); $"[LOADER][ERROR] Vulkan VideoOut translated draw setup failed: {exception.Message}");
return; return;
} }
FlushBatchedGuestCommands();
} }
uint imageIndex; uint imageIndex;
@@ -15269,6 +15335,11 @@ internal static unsafe class VulkanVideoPresenter
RecordGuestDepthForSampling(depth, shaderStage); RecordGuestDepthForSampling(depth, shaderStage);
} }
if (!texture.IsStorage && texture.GuestImage is { } sampledGuestImage)
{
RecordGuestImageForSampling(sampledGuestImage, shaderStage);
}
if (!texture.NeedsUpload) if (!texture.NeedsUpload)
{ {
continue; continue;
@@ -15476,6 +15547,76 @@ internal static unsafe class VulkanVideoPresenter
depth.Layout = ImageLayout.ShaderReadOnlyOptimal; depth.Layout = ImageLayout.ShaderReadOnlyOptimal;
} }
private void RecordGuestImageForSampling(
GuestImageResource guestImage,
PipelineStageFlags shaderStage)
{
if (guestImage.Initialized || guestImage.InitialUploadPending)
{
return;
}
var range = ColorSubresourceRange(0, Math.Max(guestImage.MipLevels, 1));
var toTransfer = new ImageMemoryBarrier
{
SType = StructureType.ImageMemoryBarrier,
DstAccessMask = AccessFlags.TransferWriteBit,
OldLayout = ImageLayout.Undefined,
NewLayout = ImageLayout.TransferDstOptimal,
SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
Image = guestImage.Image,
SubresourceRange = range,
};
_vk.CmdPipelineBarrier(
_commandBuffer,
PipelineStageFlags.TopOfPipeBit,
PipelineStageFlags.TransferBit,
0,
0,
null,
0,
null,
1,
&toTransfer);
var clearValue = new ClearColorValue(0f, 0f, 0f, 0f);
_vk.CmdClearColorImage(
_commandBuffer,
guestImage.Image,
ImageLayout.TransferDstOptimal,
&clearValue,
1,
&range);
var toShaderRead = new ImageMemoryBarrier
{
SType = StructureType.ImageMemoryBarrier,
SrcAccessMask = AccessFlags.TransferWriteBit,
DstAccessMask = AccessFlags.ShaderReadBit,
OldLayout = ImageLayout.TransferDstOptimal,
NewLayout = ImageLayout.ShaderReadOnlyOptimal,
SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
Image = guestImage.Image,
SubresourceRange = range,
};
_vk.CmdPipelineBarrier(
_commandBuffer,
PipelineStageFlags.TransferBit,
shaderStage,
0,
0,
null,
0,
null,
1,
&toShaderRead);
guestImage.Initialized = true;
}
private void RecordStandaloneGuestDepthClear(GuestDepthResource depth) private void RecordStandaloneGuestDepthClear(GuestDepthResource depth)
{ {
var depthRange = new ImageSubresourceRange( var depthRange = new ImageSubresourceRange(
@@ -7,6 +7,7 @@ using System.Buffers.Binary;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices;
namespace SharpEmu.ShaderCompiler; namespace SharpEmu.ShaderCompiler;
@@ -36,6 +37,113 @@ public static class Gen5ShaderScalarEvaluator
StringComparison.Ordinal); StringComparison.Ordinal);
private static readonly object _scalarFallbackTraceGate = new(); private static readonly object _scalarFallbackTraceGate = new();
private static readonly HashSet<(ulong Shader, uint Pc)> _tracedScalarFallbacks = []; private static readonly HashSet<(ulong Shader, uint Pc)> _tracedScalarFallbacks = [];
private static readonly HashSet<(ulong Shader, uint Pc)> _tracedDivergentDescriptors = [];
private static readonly ConditionalWeakTable<Gen5ShaderProgram, Ir.Gen5ScalarSsa> _scalarSsaCache = [];
private static readonly bool _divergentDescriptorGuard = !string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_IR_DESCRIPTOR_GUARD"),
"0",
StringComparison.Ordinal);
private static Ir.Gen5ScalarSsa GetScalarSsa(Gen5ShaderState state) =>
_scalarSsaCache.GetValue(
state.Program,
program => Ir.Gen5ScalarSsa.Build(program.Instructions, state.UserData));
/// <summary>
/// The byte offset comes from an SGPR. When the instruction that produced that
/// register is one the scalar evaluator cannot reproduce — a vector compare
/// writing VCC, say, whose value depends on per-lane data — the register still
/// holds whatever the linear walk left in it. Adding that to an otherwise valid
/// base address is how descriptors turned into addresses far out of range.
/// </summary>
private static bool IsOffsetFromUnmodelledWriter(
Gen5ShaderState state,
Gen5ShaderInstruction instruction,
Gen5ScalarMemoryControl control)
{
if (!_divergentDescriptorGuard || control.DynamicOffsetRegister is not { } offsetRegister)
{
return false;
}
var ssa = GetScalarSsa(state);
var reaching = ssa.GetReachingDefinitionAt(instruction.Pc, offsetRegister);
if (reaching.State == Ir.IrReachingState.Multiple)
{
return true;
}
if (reaching.State != Ir.IrReachingState.Single ||
reaching.DefinitionPc == uint.MaxValue)
{
return false;
}
var writer = state.Program.Instructions
.FirstOrDefault(candidate => candidate.Pc == reaching.DefinitionPc);
return writer is not null && Ir.Gen5ScalarSsa.WritesVccImplicitly(writer);
}
/// <summary>
/// A descriptor assembled from registers that differ per incoming path is not a
/// descriptor, it is whichever path the linear walk happened to take last.
/// </summary>
private static bool IsDescriptorFromDivergentMerge(
Gen5ShaderState state,
uint pc,
uint scalarBase,
uint registerCount)
{
if (!_divergentDescriptorGuard)
{
return false;
}
var ssa = GetScalarSsa(state);
if (!ssa.Graph.HasControlFlow)
{
return false;
}
for (var offset = 0u; offset < registerCount; offset++)
{
var reaching = ssa.GetReachingDefinitionAt(pc, scalarBase + offset);
if (reaching.State == Ir.IrReachingState.Multiple)
{
return true;
}
if (ssa.GetScalarAt(pc, scalarBase + offset).State == Ir.IrScalarState.Merged)
{
return true;
}
}
return false;
}
private static void TraceDivergentDescriptor(
Gen5ShaderState state,
Gen5ShaderInstruction instruction,
uint scalarBase,
ulong baseAddress)
{
lock (_scalarFallbackTraceGate)
{
if (!_tracedDivergentDescriptors.Add((state.Program.Address, instruction.Pc)))
{
return;
}
}
Console.Error.WriteLine(
$"[LOADER][WARN] agc.descriptor_divergent " +
$"shader=0x{state.Program.Address:X16} pc=0x{instruction.Pc:X} " +
$"op={instruction.Opcode} base=s{scalarBase} " +
$"linear_base_addr=0x{baseAddress:X16} (unbound instead of dereferenced)");
}
// Shaders whose empty SRT/EUD caused a null-base scalar pointer load. // Shaders whose empty SRT/EUD caused a null-base scalar pointer load.
// Host submit of those translations has lost the Vulkan device; Agc skips // Host submit of those translations has lost the Vulkan device; Agc skips
// them before QueueSubmit. // them before QueueSubmit.
@@ -1898,19 +2006,32 @@ public static class Gen5ShaderScalarEvaluator
var address = unchecked( var address = unchecked(
baseAddress + baseAddress +
byteOffset) & ~3UL; byteOffset) & ~3UL;
var descriptorDiverged = IsDescriptorFromDivergentMerge(
state,
instruction.Pc,
scalarBase.Value,
isBufferLoad ? 4u : 2u) ||
IsOffsetFromUnmodelledWriter(state, instruction, control);
if (descriptorDiverged)
{
TraceDivergentDescriptor(state, instruction, scalarBase.Value, baseAddress);
}
var bufferUnbound = var bufferUnbound =
isBufferLoad && isBufferLoad &&
(!hasBufferDescriptor || (descriptorDiverged ||
!hasBufferDescriptor ||
bufferDescriptor.SizeBytes == 0 || bufferDescriptor.SizeBytes == 0 ||
(scalarRegisters[scalarBase.Value] == 0 && (scalarRegisters[scalarBase.Value] == 0 &&
scalarRegisters[scalarBase.Value + 1] == 0 && scalarRegisters[scalarBase.Value + 1] == 0 &&
scalarBase.Value + 3 < ScalarRegisterCount && scalarBase.Value + 3 < ScalarRegisterCount &&
scalarRegisters[scalarBase.Value + 2] == 0 && scalarRegisters[scalarBase.Value + 2] == 0 &&
scalarRegisters[scalarBase.Value + 3] == 0)); scalarRegisters[scalarBase.Value + 3] == 0));
var scalarPointerUnbound = ShouldTreatScalarPointerAsUnbound( var scalarPointerUnbound = descriptorDiverged && !isBufferLoad ||
isBufferLoad, ShouldTreatScalarPointerAsUnbound(
address, isBufferLoad,
_strictScalarLoad); address,
_strictScalarLoad);
if (scalarPointerUnbound) if (scalarPointerUnbound)
{ {
TraceScalarPointerFallback( TraceScalarPointerFallback(
@@ -0,0 +1,67 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
namespace SharpEmu.ShaderCompiler.Ir;
public sealed class Gen5IrBranchResolver : IIrBranchResolver
{
public static Gen5IrBranchResolver Instance { get; } = new();
public bool IsBranch(Gen5ShaderInstruction instruction) =>
IsUnconditionalBranch(instruction) ||
IsConditional(instruction) ||
IsTerminator(instruction);
public bool IsConditional(Gen5ShaderInstruction instruction) => instruction.Opcode switch
{
"SCbranchScc0" or
"SCbranchScc1" or
"SCbranchVccz" or
"SCbranchVccnz" or
"SCbranchExecz" or
"SCbranchExecnz" or
"SCbranchCdbgsys" or
"SCbranchCdbguser" or
"SCbranchCdbgsysOrUser" or
"SCbranchCdbgsysAndUser" => true,
_ => false,
};
public bool TryGetBranchTarget(Gen5ShaderInstruction instruction, out uint targetPc)
{
targetPc = 0;
if (IsTerminator(instruction))
{
return false;
}
if (!IsUnconditionalBranch(instruction) && !IsConditional(instruction))
{
return false;
}
if (instruction.Encoding != Gen5ShaderEncoding.Sopp || instruction.Words.Count == 0)
{
return false;
}
var offset = unchecked((short)(instruction.Words[0] & 0xFFFF));
var nextPc = (long)instruction.Pc + instruction.Words.Count * sizeof(uint);
var target = nextPc + offset * sizeof(uint);
if (target < 0 || target > uint.MaxValue)
{
return false;
}
targetPc = (uint)target;
return true;
}
public static bool IsUnconditionalBranch(Gen5ShaderInstruction instruction) =>
string.Equals(instruction.Opcode, "SBranch", StringComparison.Ordinal);
public static bool IsTerminator(Gen5ShaderInstruction instruction) =>
instruction.Opcode is "SEndpgm" or "SEndpgmSaved";
}
@@ -0,0 +1,498 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using System.Linq;
namespace SharpEmu.ShaderCompiler.Ir;
public enum IrScalarState
{
Unknown,
Constant,
Merged,
}
public enum IrReachingState
{
None,
Single,
Multiple,
}
public readonly record struct IrReachingDefinition(IrReachingState State, uint DefinitionPc)
{
public static readonly IrReachingDefinition None = new(IrReachingState.None, 0);
public static readonly IrReachingDefinition Multiple = new(IrReachingState.Multiple, 0);
public static IrReachingDefinition At(uint pc) => new(IrReachingState.Single, pc);
public IrReachingDefinition Join(IrReachingDefinition other)
{
if (State == IrReachingState.None)
{
return other;
}
if (other.State == IrReachingState.None)
{
return this;
}
if (State == IrReachingState.Single &&
other.State == IrReachingState.Single &&
DefinitionPc == other.DefinitionPc)
{
return this;
}
return Multiple;
}
}
public readonly record struct IrScalarValue(IrScalarState State, uint Constant)
{
public static readonly IrScalarValue Unknown = new(IrScalarState.Unknown, 0);
public static readonly IrScalarValue Merged = new(IrScalarState.Merged, 0);
public static IrScalarValue FromConstant(uint value) => new(IrScalarState.Constant, value);
public bool IsResolved => State == IrScalarState.Constant;
public IrScalarValue Join(IrScalarValue other)
{
if (State == IrScalarState.Unknown)
{
return other;
}
if (other.State == IrScalarState.Unknown)
{
return this;
}
if (State == IrScalarState.Constant &&
other.State == IrScalarState.Constant &&
Constant == other.Constant)
{
return this;
}
return Merged;
}
}
public sealed class Gen5ScalarSsa
{
public const int ScalarRegisterCount = 256;
private Gen5ScalarSsa(
IrControlFlowGraph graph,
IReadOnlyList<IrScalarValue[]> entryState,
IReadOnlyList<IrScalarValue[]> exitState,
IReadOnlyList<IrReachingDefinition[]> entryDefinitions,
IReadOnlyDictionary<uint, int> blockByPc,
IReadOnlyList<Gen5ShaderInstruction> instructions)
{
Graph = graph;
_entryState = entryState;
_exitState = exitState;
_entryDefinitions = entryDefinitions;
_blockByPc = blockByPc;
_instructions = instructions;
}
private readonly IReadOnlyList<IrReachingDefinition[]> _entryDefinitions;
public IrControlFlowGraph Graph { get; }
private readonly IReadOnlyList<IrScalarValue[]> _entryState;
private readonly IReadOnlyList<IrScalarValue[]> _exitState;
private readonly IReadOnlyDictionary<uint, int> _blockByPc;
private readonly IReadOnlyList<Gen5ShaderInstruction> _instructions;
public static Gen5ScalarSsa Build(
IReadOnlyList<Gen5ShaderInstruction> instructions,
IReadOnlyList<uint> userData,
IIrBranchResolver? resolver = null)
{
resolver ??= Gen5IrBranchResolver.Instance;
var graph = IrControlFlowGraph.Build(instructions, resolver);
var blockCount = graph.Blocks.Count;
var entry = new List<IrScalarValue[]>(blockCount);
var exit = new List<IrScalarValue[]>(blockCount);
var defEntry = new List<IrReachingDefinition[]>(blockCount);
var defExit = new List<IrReachingDefinition[]>(blockCount);
for (var index = 0; index < blockCount; index++)
{
entry.Add(NewState());
exit.Add(NewState());
defEntry.Add(NewDefinitions());
defExit.Add(NewDefinitions());
}
if (blockCount > 0)
{
var initial = entry[0];
for (var index = 0; index < userData.Count && index < ScalarRegisterCount; index++)
{
initial[index] = IrScalarValue.FromConstant(userData[index]);
}
}
var blockByPc = new Dictionary<uint, int>();
for (var blockIndex = 0; blockIndex < blockCount; blockIndex++)
{
var range = graph.Blocks[blockIndex];
foreach (var instruction in instructions)
{
if (instruction.Pc >= range.StartPc && instruction.Pc < range.EndPc)
{
blockByPc[instruction.Pc] = blockIndex;
}
}
}
var worklist = new Queue<int>();
for (var index = 0; index < blockCount; index++)
{
worklist.Enqueue(index);
}
var visits = new int[blockCount];
const int visitLimit = 8;
while (worklist.Count > 0)
{
var blockIndex = worklist.Dequeue();
if (visits[blockIndex]++ > visitLimit)
{
continue;
}
var state = (IrScalarValue[])entry[blockIndex].Clone();
if (graph.Predecessors[blockIndex].Count > 0)
{
state = NewState();
var first = true;
foreach (var predecessor in graph.Predecessors[blockIndex])
{
var incoming = exit[predecessor];
for (var register = 0; register < ScalarRegisterCount; register++)
{
state[register] = first
? incoming[register]
: state[register].Join(incoming[register]);
}
first = false;
}
if (blockIndex == 0)
{
for (var register = 0; register < userData.Count && register < ScalarRegisterCount; register++)
{
state[register] = state[register].Join(
IrScalarValue.FromConstant(userData[register]));
}
}
}
entry[blockIndex] = state;
var definitions = NewDefinitions();
if (graph.Predecessors[blockIndex].Count == 0)
{
for (var register = 0; register < userData.Count && register < ScalarRegisterCount; register++)
{
definitions[register] = IrReachingDefinition.At(uint.MaxValue);
}
}
else
{
var first = true;
foreach (var predecessor in graph.Predecessors[blockIndex])
{
var incoming = defExit[predecessor];
for (var register = 0; register < ScalarRegisterCount; register++)
{
definitions[register] = first
? incoming[register]
: definitions[register].Join(incoming[register]);
}
first = false;
}
}
defEntry[blockIndex] = definitions;
var computed = Transfer(instructions, graph.Blocks[blockIndex], state);
var computedDefinitions = TransferDefinitions(
instructions,
graph.Blocks[blockIndex],
definitions);
var changed = !SameState(exit[blockIndex], computed) ||
!SameDefinitions(defExit[blockIndex], computedDefinitions);
exit[blockIndex] = computed;
defExit[blockIndex] = computedDefinitions;
if (changed)
{
foreach (var successor in graph.Successors[blockIndex])
{
worklist.Enqueue(successor);
}
}
}
return new Gen5ScalarSsa(graph, entry, exit, defEntry, blockByPc, instructions);
}
public IrScalarValue GetScalarAt(uint pc, uint register)
{
if (register >= ScalarRegisterCount || !_blockByPc.TryGetValue(pc, out var blockIndex))
{
return IrScalarValue.Unknown;
}
var state = (IrScalarValue[])_entryState[blockIndex].Clone();
var range = _graphRange(blockIndex);
foreach (var instruction in _instructions)
{
if (instruction.Pc < range.StartPc || instruction.Pc >= range.EndPc)
{
continue;
}
if (instruction.Pc >= pc)
{
break;
}
Apply(instruction, state);
}
return state[register];
}
public IrReachingDefinition GetReachingDefinitionAt(uint pc, uint register)
{
if (register >= ScalarRegisterCount || !_blockByPc.TryGetValue(pc, out var blockIndex))
{
return IrReachingDefinition.None;
}
var definitions = (IrReachingDefinition[])_entryDefinitions[blockIndex].Clone();
var range = _graphRange(blockIndex);
foreach (var instruction in _instructions)
{
if (instruction.Pc < range.StartPc || instruction.Pc >= range.EndPc)
{
continue;
}
if (instruction.Pc >= pc)
{
break;
}
ApplyDefinitions(instruction, definitions);
}
return definitions[register];
}
public bool IsInsideDivergentMerge(uint pc) =>
_blockByPc.TryGetValue(pc, out var blockIndex) &&
_graphPredecessorCount(blockIndex) > 1;
private IrBlockRange _graphRange(int blockIndex) => Graph.Blocks[blockIndex];
private int _graphPredecessorCount(int blockIndex) => Graph.Predecessors[blockIndex].Count;
private static IrScalarValue[] NewState()
{
var state = new IrScalarValue[ScalarRegisterCount];
for (var index = 0; index < state.Length; index++)
{
state[index] = IrScalarValue.Unknown;
}
return state;
}
private static IrReachingDefinition[] NewDefinitions()
{
var definitions = new IrReachingDefinition[ScalarRegisterCount];
for (var index = 0; index < definitions.Length; index++)
{
definitions[index] = IrReachingDefinition.None;
}
return definitions;
}
private static bool SameDefinitions(IrReachingDefinition[] left, IrReachingDefinition[] right)
{
for (var index = 0; index < left.Length; index++)
{
if (!left[index].Equals(right[index]))
{
return false;
}
}
return true;
}
private static IrReachingDefinition[] TransferDefinitions(
IReadOnlyList<Gen5ShaderInstruction> instructions,
IrBlockRange range,
IrReachingDefinition[] entry)
{
var definitions = (IrReachingDefinition[])entry.Clone();
foreach (var instruction in instructions)
{
if (instruction.Pc < range.StartPc || instruction.Pc >= range.EndPc)
{
continue;
}
ApplyDefinitions(instruction, definitions);
}
return definitions;
}
public const uint VccLo = 106;
public const uint VccHi = 107;
/// <summary>
/// VOPC compares and the VOP2 carry forms write VCC without naming it: the ISA
/// makes the destination implicit in the encoding, so the decoded instruction
/// carries no destination operand for it. Modelling that here (rather than in
/// the shared decoder) keeps the linear evaluator's behaviour untouched while
/// letting the dataflow see that VCC was written.
/// </summary>
public static bool WritesVccImplicitly(Gen5ShaderInstruction instruction)
{
if (instruction.Encoding == Gen5ShaderEncoding.Vopc)
{
return true;
}
return instruction.Encoding == Gen5ShaderEncoding.Vop2 &&
instruction.Opcode is
"VAddCoCiU32" or
"VSubCoCiU32" or
"VSubrevCoCiU32";
}
private static void ApplyDefinitions(
Gen5ShaderInstruction instruction,
IrReachingDefinition[] definitions)
{
foreach (var destination in instruction.Destinations)
{
if (destination.Kind != Gen5OperandKind.ScalarRegister ||
destination.Value >= ScalarRegisterCount)
{
continue;
}
definitions[destination.Value] = IrReachingDefinition.At(instruction.Pc);
}
if (WritesVccImplicitly(instruction))
{
definitions[VccLo] = IrReachingDefinition.At(instruction.Pc);
definitions[VccHi] = IrReachingDefinition.At(instruction.Pc);
}
}
private static bool SameState(IrScalarValue[] left, IrScalarValue[] right)
{
for (var index = 0; index < left.Length; index++)
{
if (!left[index].Equals(right[index]))
{
return false;
}
}
return true;
}
private static IrScalarValue[] Transfer(
IReadOnlyList<Gen5ShaderInstruction> instructions,
IrBlockRange range,
IrScalarValue[] entry)
{
var state = (IrScalarValue[])entry.Clone();
foreach (var instruction in instructions)
{
if (instruction.Pc < range.StartPc || instruction.Pc >= range.EndPc)
{
continue;
}
Apply(instruction, state);
}
return state;
}
private static void Apply(Gen5ShaderInstruction instruction, IrScalarValue[] state)
{
var resolved = ResolveResult(instruction, state);
foreach (var destination in instruction.Destinations)
{
if (destination.Kind != Gen5OperandKind.ScalarRegister ||
destination.Value >= ScalarRegisterCount)
{
continue;
}
state[destination.Value] = resolved;
}
}
private static IrScalarValue ResolveResult(
Gen5ShaderInstruction instruction,
IrScalarValue[] state)
{
if (instruction.Destinations.Count != 1)
{
return IrScalarValue.Unknown;
}
return instruction.Opcode switch
{
"SMov" or "SMovB32" => Source(instruction, state, 0),
_ => IrScalarValue.Unknown,
};
}
private static IrScalarValue Source(
Gen5ShaderInstruction instruction,
IrScalarValue[] state,
int index)
{
if (index >= instruction.Sources.Count)
{
return IrScalarValue.Unknown;
}
var source = instruction.Sources[index];
return source.Kind switch
{
Gen5OperandKind.ScalarRegister when source.Value < ScalarRegisterCount =>
state[source.Value],
Gen5OperandKind.LiteralConstant => IrScalarValue.FromConstant(source.Value),
_ => IrScalarValue.Unknown,
};
}
}
@@ -0,0 +1,161 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using System.Linq;
namespace SharpEmu.ShaderCompiler.Ir;
public readonly record struct IrBlockRange(uint StartPc, uint EndPc);
public sealed class IrControlFlowGraph
{
private IrControlFlowGraph(
IReadOnlyList<IrBlockRange> blocks,
IReadOnlyDictionary<uint, int> blockByStartPc,
IReadOnlyList<IReadOnlyList<int>> successors,
IReadOnlyList<IReadOnlyList<int>> predecessors,
IReadOnlySet<int> loopHeaders)
{
Blocks = blocks;
BlockByStartPc = blockByStartPc;
Successors = successors;
Predecessors = predecessors;
LoopHeaders = loopHeaders;
}
public IReadOnlyList<IrBlockRange> Blocks { get; }
public IReadOnlyDictionary<uint, int> BlockByStartPc { get; }
public IReadOnlyList<IReadOnlyList<int>> Successors { get; }
public IReadOnlyList<IReadOnlyList<int>> Predecessors { get; }
public IReadOnlySet<int> LoopHeaders { get; }
public bool HasControlFlow => Blocks.Count > 1;
public static IrControlFlowGraph Build(
IReadOnlyList<Gen5ShaderInstruction> instructions,
IIrBranchResolver resolver)
{
var leaders = new SortedSet<uint>();
if (instructions.Count > 0)
{
leaders.Add(instructions[0].Pc);
}
for (var index = 0; index < instructions.Count; index++)
{
var instruction = instructions[index];
if (!resolver.IsBranch(instruction))
{
continue;
}
if (resolver.TryGetBranchTarget(instruction, out var target))
{
leaders.Add(target);
}
if (index + 1 < instructions.Count)
{
leaders.Add(instructions[index + 1].Pc);
}
}
var ordered = leaders.ToList();
var ranges = new List<IrBlockRange>(ordered.Count);
var byStart = new Dictionary<uint, int>();
for (var index = 0; index < ordered.Count; index++)
{
var start = ordered[index];
var end = index + 1 < ordered.Count
? ordered[index + 1]
: instructions.Count > 0 ? instructions[^1].Pc + 1 : start;
byStart[start] = ranges.Count;
ranges.Add(new IrBlockRange(start, end));
}
var successors = new List<List<int>>(ranges.Count);
var predecessors = new List<List<int>>(ranges.Count);
for (var index = 0; index < ranges.Count; index++)
{
successors.Add([]);
predecessors.Add([]);
}
for (var blockIndex = 0; blockIndex < ranges.Count; blockIndex++)
{
var range = ranges[blockIndex];
var last = instructions
.Where(candidate => candidate.Pc >= range.StartPc && candidate.Pc < range.EndPc)
.LastOrDefault();
if (last is null)
{
continue;
}
var isBranch = resolver.IsBranch(last);
var hasTarget = isBranch && resolver.TryGetBranchTarget(last, out var target) &&
byStart.TryGetValue(target, out var targetIndex);
if (hasTarget)
{
_ = resolver.TryGetBranchTarget(last, out var resolved);
Link(successors, predecessors, blockIndex, byStart[resolved]);
}
var fallsThrough = !isBranch || resolver.IsConditional(last);
if (fallsThrough && blockIndex + 1 < ranges.Count)
{
Link(successors, predecessors, blockIndex, blockIndex + 1);
}
}
var headers = new HashSet<int>();
for (var blockIndex = 0; blockIndex < ranges.Count; blockIndex++)
{
foreach (var successor in successors[blockIndex])
{
if (successor <= blockIndex)
{
headers.Add(successor);
}
}
}
return new IrControlFlowGraph(
ranges,
byStart,
successors.Select(list => (IReadOnlyList<int>)list).ToList(),
predecessors.Select(list => (IReadOnlyList<int>)list).ToList(),
headers);
}
private static void Link(
List<List<int>> successors,
List<List<int>> predecessors,
int from,
int to)
{
if (!successors[from].Contains(to))
{
successors[from].Add(to);
}
if (!predecessors[to].Contains(from))
{
predecessors[to].Add(from);
}
}
}
public interface IIrBranchResolver
{
bool IsBranch(Gen5ShaderInstruction instruction);
bool IsConditional(Gen5ShaderInstruction instruction);
bool TryGetBranchTarget(Gen5ShaderInstruction instruction, out uint targetPc);
}
@@ -75,49 +75,6 @@ public sealed class AvPlayerPathTests : IDisposable
AssertPathIsInsideApp0(resolved); AssertPathIsInsideApp0(resolved);
} }
[Theory]
[InlineData(false, "ffmpeg", "ffprobe")]
[InlineData(true, "ffmpeg.exe", "ffprobe.exe")]
public void MediaToolLookupUsesPlatformNames(
bool isWindows,
string ffmpegName,
string ffprobeName)
{
var toolDirectory = Path.Combine(_tempRoot, "Media Tools");
Directory.CreateDirectory(toolDirectory);
var ffmpeg = Path.Combine(toolDirectory, ffmpegName);
File.WriteAllBytes(ffmpeg, []);
var resolved = AvPlayerExports.FindFfmpeg(
configured: null,
searchPath: $"\"{toolDirectory}\"",
isWindows);
Assert.Equal(ffmpeg, resolved);
Assert.Equal(
Path.Combine(toolDirectory, ffprobeName),
AvPlayerExports.GetFfprobePath(ffmpeg, isWindows));
}
[Theory]
[InlineData(false, "ffmpeg")]
[InlineData(true, "ffmpeg.exe")]
public void MediaToolLookupFindsPackagedBinary(bool isWindows, string executable)
{
var publishDirectory = Path.Combine(_tempRoot, "publish");
Directory.CreateDirectory(Path.Combine(publishDirectory, "ffmpeg"));
var ffmpeg = Path.Combine(publishDirectory, "ffmpeg", executable);
File.WriteAllBytes(ffmpeg, []);
Assert.Equal(
ffmpeg,
AvPlayerExports.FindFfmpeg(
configured: null,
searchPath: null,
isWindows,
publishDirectory));
}
[Fact] [Fact]
public void RelativeFileUriCannotEscapeApp0() public void RelativeFileUriCannotEscapeApp0()
{ {
@@ -0,0 +1,100 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.ObjectModel;
using SharpEmu.GUI;
using Xunit;
namespace SharpEmu.Libs.Tests.GUI;
public sealed class GameLibraryReconcilerTests
{
[Fact]
public void Reconcile_PreservesExistingEntriesAndAppliesMetadataChanges()
{
var retained = CreateGame("retained", name: "Old name", version: "01.000");
var removed = CreateGame("removed");
var scannedRetained = CreateGame(
"retained",
name: "New name",
version: "02.000");
var added = CreateGame("added");
var result = GameLibraryReconciler.Reconcile(
[retained, removed],
[scannedRetained, added]);
Assert.Equal(2, result.Games.Count);
Assert.Same(retained, result.Games[0]);
Assert.Same(added, result.Games[1]);
Assert.Equal("New name", retained.Name);
Assert.Equal("02.000", retained.Version);
Assert.DoesNotContain(removed, result.Games);
}
[Fact]
public void Reconcile_ChangedCoverAndBackgroundReloadsExistingEntry()
{
var retained = CreateGame(
"retained",
coverPath: AssetPath("old-cover.png"),
backgroundPath: AssetPath("old-background.png"));
var scanned = CreateGame(
"retained",
coverPath: AssetPath("new-cover.png"),
backgroundPath: AssetPath("new-background.png"));
var result = GameLibraryReconciler.Reconcile([retained], [scanned]);
Assert.Same(retained, Assert.Single(result.Games));
Assert.Same(retained, Assert.Single(result.CoversToLoad));
Assert.Contains(retained, result.BackgroundsChanged);
Assert.Equal(scanned.CoverPath, retained.CoverPath);
Assert.Equal(scanned.BackgroundPath, retained.BackgroundPath);
}
[Fact]
public void ReconcileVisibleGames_UsesMinimalIdentityPreservingChanges()
{
var first = CreateGame("first");
var second = CreateGame("second");
var removed = CreateGame("removed");
var added = CreateGame("added");
var visible = new ObservableCollection<GameEntry>
{
first,
second,
removed,
};
GameLibraryReconciler.ReconcileVisibleGames(
visible,
[second, first, added]);
Assert.Equal([second, first, added], visible);
Assert.Same(second, visible[0]);
Assert.Same(first, visible[1]);
Assert.Same(added, visible[2]);
}
private static GameEntry CreateGame(
string id,
string? name = null,
string? version = null,
string? coverPath = null,
string? backgroundPath = null)
=> new(
name ?? id,
$"PPSA-{id}",
version,
GamePath(id),
1,
coverPath,
backgroundPath);
private static string GamePath(string id)
=> Path.GetFullPath(Path.Combine("library-tests", id, "eboot.bin"));
private static string AssetPath(string name)
=> Path.GetFullPath(Path.Combine("library-tests", "assets", name));
}
@@ -0,0 +1,38 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.GUI;
using Xunit;
namespace SharpEmu.Libs.Tests.GUI;
public sealed class GameLibraryWatcherTests
{
[Fact]
public async Task Watch_FileCreation_RequestsRefresh()
{
var directory = Path.Combine(
Path.GetTempPath(),
$"sharpemu-library-watcher-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
try
{
using var watcher = new GameLibraryWatcher(TimeSpan.FromMilliseconds(25));
var refreshRequested = new TaskCompletionSource(
TaskCreationOptions.RunContinuationsAsynchronously);
watcher.RefreshRequested += (_, _) => refreshRequested.TrySetResult();
watcher.Watch([directory]);
await File.WriteAllTextAsync(
Path.Combine(directory, "eboot.bin"),
"test");
await refreshRequested.Task.WaitAsync(TimeSpan.FromSeconds(5));
}
finally
{
Directory.Delete(directory, recursive: true);
}
}
}
@@ -95,6 +95,67 @@ public sealed class GuiSettingsTests
Assert.Equal(["SHARPEMU_TRACE"], settings.EnvironmentToggles); Assert.Equal(["SHARPEMU_TRACE"], settings.EnvironmentToggles);
} }
[Fact]
public void NormalizeFromJson_AllLauncherOptions_ArePreserved()
{
const string json = """
{
"LogLevel": "Debug",
"ImportTraceLimit": 96,
"StrictDynlibResolution": true,
"LogToFile": true,
"LogFilePath": "C:\\Logs\\sharpemu.log",
"OverrideLogFile": true,
"PlayTitleMusic": false,
"EmulatorPath": "C:\\SharpEmu\\SharpEmu.exe",
"Language": "ru",
"DefaultProfile": "Player",
"DiscordRichPresence": false,
"CheckForUpdatesOnStartup": false,
"WindowMode": "Borderless",
"Resolution": "2560x1440",
"DisplayIndex": 2,
"RefreshRate": 144,
"ScalingMode": "Integer",
"VSync": false,
"HdrMode": "On",
"EnvironmentToggles": [
"SHARPEMU_VK_VALIDATION",
"SHARPEMU_GUEST_IMAGE_CPU_SYNC"
],
"RenderResolutionScale": 0.5,
"DiscordClientId": "999"
}
""";
var settings = GuiSettings.NormalizeFromJson(json);
Assert.Equal("Debug", settings.LogLevel);
Assert.Equal(96, settings.ImportTraceLimit);
Assert.True(settings.StrictDynlibResolution);
Assert.True(settings.LogToFile);
Assert.Equal("C:\\Logs\\sharpemu.log", settings.LogFilePath);
Assert.True(settings.OverrideLogFile);
Assert.False(settings.PlayTitleMusic);
Assert.Equal("C:\\SharpEmu\\SharpEmu.exe", settings.EmulatorPath);
Assert.Equal("ru", settings.Language);
Assert.Equal("Player", settings.DefaultProfile);
Assert.False(settings.DiscordRichPresence);
Assert.False(settings.CheckForUpdatesOnStartup);
Assert.Equal("Borderless", settings.WindowMode);
Assert.Equal("2560x1440", settings.Resolution);
Assert.Equal(2, settings.DisplayIndex);
Assert.Equal(144, settings.RefreshRate);
Assert.Equal("Integer", settings.ScalingMode);
Assert.False(settings.VSync);
Assert.Equal("On", settings.HdrMode);
Assert.Equal(
["SHARPEMU_VK_VALIDATION", "SHARPEMU_GUEST_IMAGE_CPU_SYNC"],
settings.EnvironmentToggles);
Assert.Equal(0.5, settings.RenderResolutionScale);
Assert.Equal("999", settings.DiscordClientId);
}
// An empty Discord client ID intentionally disables Rich Presence. // An empty Discord client ID intentionally disables Rich Presence.
[Fact] [Fact]
public void NormalizeFromJson_EmptyDiscordClientId_IsPreservedNotNormalized() public void NormalizeFromJson_EmptyDiscordClientId_IsPreservedNotNormalized()
@@ -0,0 +1,52 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.GUI;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Xunit;
namespace SharpEmu.Libs.Tests.GUI;
public sealed class LibraryTileCollectionTests
{
[Fact]
public void KeepsAddFolderTileAfterVisibleGames()
{
var games = new ObservableCollection<GameEntry>();
var tiles = new LibraryTileCollection(games);
var first = CreateGame("First");
var second = CreateGame("Second");
games.Add(first);
games.Add(second);
Assert.Equal(3, tiles.Count);
Assert.True(tiles is IList { IsReadOnly: true });
Assert.Same(first, tiles[0]);
Assert.Same(second, tiles[1]);
Assert.Same(AddFolderTile.Instance, tiles[2]);
}
[Fact]
public void ForwardsGameChangesAtTheirOriginalIndices()
{
var games = new ObservableCollection<GameEntry>();
var tiles = new LibraryTileCollection(games);
NotifyCollectionChangedEventArgs? change = null;
tiles.CollectionChanged += (_, args) => change = args;
var game = CreateGame("Game");
games.Add(game);
Assert.NotNull(change);
Assert.Equal(NotifyCollectionChangedAction.Add, change.Action);
Assert.Equal(0, change.NewStartingIndex);
Assert.Same(game, Assert.Single(change.NewItems!.Cast<GameEntry>()));
Assert.Same(AddFolderTile.Instance, tiles[1]);
}
private static GameEntry CreateGame(string name) =>
new(name, null, null, $"/games/{name}/eboot.bin", 0, null, null);
}
@@ -0,0 +1,198 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using Avalonia.Controls;
using Avalonia.Data;
using SharpEmu.GUI;
using System.Text.Json;
using Xunit;
namespace SharpEmu.Libs.Tests.GUI;
public sealed class LocalizationTests : IDisposable
{
private readonly string _languagesDirectory = Path.Combine(
Path.GetTempPath(),
$"sharpemu-localization-{Guid.NewGuid():N}");
public LocalizationTests()
{
Directory.CreateDirectory(_languagesDirectory);
}
[Fact]
public void Load_RaisesNotificationsForCurrentCodeAndIndexer()
{
var localization = new Localization(_languagesDirectory);
var changedProperties = new List<string?>();
localization.PropertyChanged += (_, args) =>
changedProperties.Add(args.PropertyName);
localization.Load("ru");
Assert.Equal("ru", localization.CurrentCode);
Assert.Contains(nameof(Localization.CurrentCode), changedProperties);
Assert.Contains("Item", changedProperties);
}
[Fact]
public void IndexerBinding_UpdatesWhenLanguageChanges()
{
var localization = new Localization(_languagesDirectory);
localization.Load("en");
var englishLibraryLabel = localization.Get("Page.Library");
localization.Load("ru");
var russianLibraryLabel = localization.Get("Page.Library");
Assert.NotEqual(englishLibraryLabel, russianLibraryLabel);
localization.Load("en");
var text = new TextBlock();
text.Bind(
TextBlock.TextProperty,
new Binding("[Page.Library]") { Source = localization });
Assert.Equal(englishLibraryLabel, text.Text);
localization.Load("ru");
Assert.Equal(russianLibraryLabel, text.Text);
}
[Fact]
public void LocalizedChoice_UpdatesLabelWithoutReplacingStableValue()
{
var localization = new Localization(_languagesDirectory);
var choice = LocalizedChoice.FromKey(
"Native",
"Options.CpuEngine.Native");
var changedProperties = new List<string?>();
choice.PropertyChanged += (_, args) =>
changedProperties.Add(args.PropertyName);
localization.Load("en");
choice.Refresh(localization);
var englishLabel = choice.Label;
localization.Load("ru");
choice.Refresh(localization);
Assert.Equal("Native", choice.Value);
Assert.NotEqual(englishLabel, choice.Label);
Assert.Equal(localization.Get("Options.CpuEngine.Native"), choice.Label);
Assert.Contains(nameof(LocalizedChoice.Label), changedProperties);
}
[Fact]
public void ComboBoxSelection_KeepsLiveLocalizedChoiceAsSelectionBoxItem()
{
var localization = new Localization(_languagesDirectory);
var choice = LocalizedChoice.FromKey(
"Native",
"Options.CpuEngine.Native");
localization.Load("en");
choice.Refresh(localization);
var comboBox = new ComboBox
{
ItemsSource = new[] { choice },
SelectedIndex = 0,
};
Assert.Same(choice, comboBox.SelectionBoxItem);
localization.Load("ru");
choice.Refresh(localization);
Assert.Same(choice, comboBox.SelectionBoxItem);
Assert.Equal(localization.Get("Options.CpuEngine.Native"), choice.Label);
}
[Fact]
public void EmbeddedLanguages_ContainEveryEnglishOptionsKey()
{
var assembly = typeof(Localization).Assembly;
var resourceNames = assembly.GetManifestResourceNames()
.Where(name =>
name.StartsWith("Languages.", StringComparison.Ordinal) &&
name.EndsWith(".json", StringComparison.Ordinal))
.Order()
.ToArray();
var english = ReadEmbeddedLanguage(assembly, "Languages.en.json");
var optionKeys = english.Keys
.Where(key => key.StartsWith("Options.", StringComparison.Ordinal))
.ToHashSet(StringComparer.Ordinal);
foreach (var resourceName in resourceNames)
{
var language = ReadEmbeddedLanguage(assembly, resourceName);
var missing = optionKeys
.Where(key => !language.ContainsKey(key))
.Order()
.ToArray();
var empty = optionKeys
.Where(key =>
language.TryGetValue(key, out var value) &&
string.IsNullOrWhiteSpace(value))
.Order()
.ToArray();
Assert.True(
missing.Length == 0,
$"{resourceName} is missing option keys: {string.Join(", ", missing)}");
Assert.True(
empty.Length == 0,
$"{resourceName} has empty option values: {string.Join(", ", empty)}");
}
}
[Theory]
[InlineData("en")]
[InlineData("ru")]
public void LooseLanguageFile_OverridesEmbeddedValuesWithoutReplacingThem(
string languageCode)
{
var localization = new Localization(_languagesDirectory);
localization.Load(languageCode);
var embeddedOptionsLabel = localization.Get("Page.Options");
File.WriteAllText(
Path.Combine(_languagesDirectory, $"{languageCode}.json"),
$$"""
{
"_languageName": "Test {{languageCode}}",
"Page.Library": "Custom library"
}
""");
localization.Load(languageCode);
Assert.Equal("Custom library", localization.Get("Page.Library"));
Assert.Equal(embeddedOptionsLabel, localization.Get("Page.Options"));
}
[Fact]
public void MissingLanguage_FallsBackToEnglish()
{
var localization = new Localization(_languagesDirectory);
localization.Load("en");
var englishLibraryLabel = localization.Get("Page.Library");
localization.Load("missing");
Assert.Equal("missing", localization.CurrentCode);
Assert.Equal(englishLibraryLabel, localization.Get("Page.Library"));
}
public void Dispose()
{
Directory.Delete(_languagesDirectory, recursive: true);
}
private static Dictionary<string, string> ReadEmbeddedLanguage(
System.Reflection.Assembly assembly,
string resourceName)
{
using var stream = assembly.GetManifestResourceStream(resourceName);
Assert.NotNull(stream);
return JsonSerializer.Deserialize<Dictionary<string, string>>(stream)
?? throw new InvalidDataException($"Could not parse {resourceName}.");
}
}
@@ -0,0 +1,27 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using Avalonia.Controls;
using SharpEmu.GUI;
using Xunit;
namespace SharpEmu.Libs.Tests.GUI;
public sealed class WindowChromeTests
{
[Theory]
[InlineData(WindowState.Normal, "crop_square", "Maximize", "Maximize window")]
[InlineData(WindowState.Maximized, "filter_none", "Restore", "Restore window")]
public void GetMaximizeButtonState_ReturnsConsistentVisualAndAccessibleState(
WindowState windowState,
string expectedGlyph,
string expectedToolTip,
string expectedAutomationName)
{
var state = MainWindow.GetMaximizeButtonState(windowState);
Assert.Equal(expectedGlyph, state.Glyph);
Assert.Equal(expectedToolTip, state.ToolTip);
Assert.Equal(expectedAutomationName, state.AutomationName);
}
}
@@ -2,18 +2,18 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary; using System.Buffers.Binary;
using SharpEmu.Libs.Bink; using SharpEmu.Libs.Media;
using Xunit; using Xunit;
namespace SharpEmu.Libs.Tests.Bink; namespace SharpEmu.Libs.Tests.Media;
public sealed class Bink2MovieBridgeTests : IDisposable public sealed class HostMovieBridgeTests : IDisposable
{ {
private readonly string _tempDirectory = Path.Combine( private readonly string _tempDirectory = Path.Combine(
Path.GetTempPath(), Path.GetTempPath(),
$"sharpemu-bink-{Guid.NewGuid():N}"); $"sharpemu-bink-{Guid.NewGuid():N}");
public Bink2MovieBridgeTests() public HostMovieBridgeTests()
{ {
Directory.CreateDirectory(_tempDirectory); Directory.CreateDirectory(_tempDirectory);
} }
@@ -23,7 +23,7 @@ public sealed class Bink2MovieBridgeTests : IDisposable
{ {
var path = WriteHeader("KB2j"u8, 3840, 2160, 30_000, 1_001); var path = WriteHeader("KB2j"u8, 3840, 2160, 30_000, 1_001);
Assert.True(Bink2MovieBridge.TryReadBinkInfo(path, out var info)); Assert.True(HostMovieBridge.TryReadBinkInfo(path, out var info));
Assert.Equal(3840u, info.Width); Assert.Equal(3840u, info.Width);
Assert.Equal(2160u, info.Height); Assert.Equal(2160u, info.Height);
Assert.Equal(30_000u, info.FramesPerSecondNumerator); Assert.Equal(30_000u, info.FramesPerSecondNumerator);
@@ -43,7 +43,7 @@ public sealed class Bink2MovieBridgeTests : IDisposable
60, 60,
1); 1);
Assert.True(Bink2MovieBridge.TryReadBinkInfo(path, out _)); Assert.True(HostMovieBridge.TryReadBinkInfo(path, out _));
} }
[Fact] [Fact]
@@ -51,7 +51,7 @@ public sealed class Bink2MovieBridgeTests : IDisposable
{ {
var path = WriteHeader("KB2j"u8, 1920, 1080, 60, 0); var path = WriteHeader("KB2j"u8, 1920, 1080, 60, 0);
Assert.False(Bink2MovieBridge.TryReadBinkInfo(path, out _)); Assert.False(HostMovieBridge.TryReadBinkInfo(path, out _));
} }
private string WriteHeader( private string WriteHeader(
@@ -1,17 +1,17 @@
// Copyright (C) 2026 SharpEmu Emulator Project // Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Libs.Bink; using SharpEmu.Libs.Media;
using Xunit; using Xunit;
namespace SharpEmu.Libs.Tests.Bink; namespace SharpEmu.Libs.Tests.Media;
public sealed class BinkFramePlaybackTests public sealed class MediaFramePlaybackTests
{ {
[Fact] [Fact]
public void FramesAdvanceAccordingToMovieClock() public void FramesAdvanceAccordingToMovieClock()
{ {
using var playback = new BinkFramePlayback(new SequenceDecoder(1, 2, 3)); using var playback = new MediaFramePlayback(new SequenceDecoder(1, 2, 3));
Assert.Equal(1, WaitForAdvancedFrame(playback)[0]); Assert.Equal(1, WaitForAdvancedFrame(playback)[0]);
Assert.True(playback.TryGetFrame(true, out var heldFrame, out var advanced)); Assert.True(playback.TryGetFrame(true, out var heldFrame, out var advanced));
@@ -22,7 +22,7 @@ public sealed class BinkFramePlaybackTests
Assert.Equal(3, WaitForAdvancedFrame(playback)[0]); Assert.Equal(3, WaitForAdvancedFrame(playback)[0]);
} }
private static byte[] WaitForAdvancedFrame(BinkFramePlayback playback) private static byte[] WaitForAdvancedFrame(MediaFramePlayback playback)
{ {
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2); var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2);
while (DateTime.UtcNow < deadline) while (DateTime.UtcNow < deadline)
@@ -41,7 +41,7 @@ public sealed class BinkFramePlaybackTests
[Fact] [Fact]
public void FirstFrameWaitsUntilPresentationStarts() public void FirstFrameWaitsUntilPresentationStarts()
{ {
using var playback = new BinkFramePlayback(new SequenceDecoder(1, 2)); using var playback = new MediaFramePlayback(new SequenceDecoder(1, 2));
var first = WaitForFrame(playback, advanceClock: false); var first = WaitForFrame(playback, advanceClock: false);
Assert.Equal(1, first[0]); Assert.Equal(1, first[0]);
@@ -58,7 +58,7 @@ public sealed class BinkFramePlaybackTests
} }
private static byte[] WaitForFrame( private static byte[] WaitForFrame(
BinkFramePlayback playback, MediaFramePlayback playback,
bool advanceClock) bool advanceClock)
{ {
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2); var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2);
@@ -75,7 +75,7 @@ public sealed class BinkFramePlaybackTests
throw new TimeoutException("The decoder did not produce a frame."); throw new TimeoutException("The decoder did not produce a frame.");
} }
private sealed class SequenceDecoder(params byte[] values) : IBinkFrameDecoder private sealed class SequenceDecoder(params byte[] values) : IMediaFrameDecoder
{ {
private int _index; private int _index;
@@ -0,0 +1,90 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Ir;
using Xunit;
namespace SharpEmu.ShaderCompiler.Tests;
public sealed class Gen5ImplicitVccTests
{
private static Gen5ShaderInstruction Vopc(uint pc, string opcode = "VCmpEqU32") =>
new(pc, Gen5ShaderEncoding.Vopc, opcode, [0u], [], [], null);
private static Gen5ShaderInstruction Vop2(uint pc, string opcode) =>
new(pc, Gen5ShaderEncoding.Vop2, opcode, [0u], [], [Gen5Operand.Vector(0)], null);
private static Gen5ShaderInstruction Nop(uint pc) =>
new(pc, Gen5ShaderEncoding.Sop1, "SNop", [0u], [], [], null);
[Fact]
public void VopcIsRecognisedAsAnImplicitVccWriter()
{
Assert.True(Gen5ScalarSsa.WritesVccImplicitly(Vopc(0)));
Assert.True(Gen5ScalarSsa.WritesVccImplicitly(Vopc(0, "VCmpLtF32")));
}
[Fact]
public void Vop2CarryFormsAreRecognised()
{
Assert.True(Gen5ScalarSsa.WritesVccImplicitly(Vop2(0, "VAddCoCiU32")));
Assert.True(Gen5ScalarSsa.WritesVccImplicitly(Vop2(0, "VSubCoCiU32")));
Assert.True(Gen5ScalarSsa.WritesVccImplicitly(Vop2(0, "VSubrevCoCiU32")));
}
[Fact]
public void PlainVop2DoesNotWriteVcc()
{
Assert.False(Gen5ScalarSsa.WritesVccImplicitly(Vop2(0, "VAddF32")));
Assert.False(Gen5ScalarSsa.WritesVccImplicitly(Nop(0)));
}
[Fact]
public void VopcDefinesBothVccHalves()
{
List<Gen5ShaderInstruction> program = [Vopc(0), Nop(4)];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var low = ssa.GetReachingDefinitionAt(4, Gen5ScalarSsa.VccLo);
var high = ssa.GetReachingDefinitionAt(4, Gen5ScalarSsa.VccHi);
Assert.Equal(IrReachingState.Single, low.State);
Assert.Equal(0u, low.DefinitionPc);
Assert.Equal(IrReachingState.Single, high.State);
Assert.Equal(0u, high.DefinitionPc);
}
[Fact]
public void WithoutTheImplicitWriteVccWouldLookUndefined()
{
// The regression this models: before implicit VCC was tracked the offset
// register reported "none" and its stale value was used as a byte offset.
List<Gen5ShaderInstruction> program = [Nop(0), Nop(4)];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrReachingState.None, ssa.GetReachingDefinitionAt(4, Gen5ScalarSsa.VccLo).State);
}
[Fact]
public void VccWrittenOnBothBranchesBecomesMultiple()
{
List<Gen5ShaderInstruction> program =
[
new(0, Gen5ShaderEncoding.Sopp, "SCbranchScc0", [2u], [], [], null),
Vopc(4),
new(8, Gen5ShaderEncoding.Sopp, "SBranch", [1u], [], [], null),
Vopc(12),
Nop(16),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(
IrReachingState.Multiple,
ssa.GetReachingDefinitionAt(16, Gen5ScalarSsa.VccLo).State);
}
}
@@ -0,0 +1,142 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Ir;
using Xunit;
namespace SharpEmu.ShaderCompiler.Tests;
public sealed class Gen5ReachingDefinitionTests
{
private static Gen5ShaderInstruction Load(uint pc, uint destination) =>
new(
pc,
Gen5ShaderEncoding.Smem,
"SLoadDwordx4",
[0u, 0u],
[Gen5Operand.Scalar(0)],
[Gen5Operand.Scalar(destination)],
null);
private static Gen5ShaderInstruction Nop(uint pc) =>
new(pc, Gen5ShaderEncoding.Sop1, "SNop", [0u], [], [], null);
private static Gen5ShaderInstruction Branch(uint pc, string opcode, short wordOffset) =>
new(
pc,
Gen5ShaderEncoding.Sopp,
opcode,
[unchecked((uint)(ushort)wordOffset)],
[],
[],
null);
[Fact]
public void SingleDefinitionIsTracked()
{
List<Gen5ShaderInstruction> program = [Load(0, 16), Nop(4)];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var reaching = ssa.GetReachingDefinitionAt(4, 16);
Assert.Equal(IrReachingState.Single, reaching.State);
Assert.Equal(0u, reaching.DefinitionPc);
}
[Fact]
public void TwoDefinitionsOnDifferentPathsBecomeMultiple()
{
// The case that produced garbage descriptors: the same register is
// written on both sides of a branch and read after the join.
List<Gen5ShaderInstruction> program =
[
Branch(0, "SCbranchScc0", 2),
Load(4, 16),
Branch(8, "SBranch", 1),
Load(12, 16),
Nop(16),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrReachingState.Multiple, ssa.GetReachingDefinitionAt(16, 16).State);
}
[Fact]
public void DefinitionOnOnlyOnePathIsAlsoMultipleAtTheJoin()
{
List<Gen5ShaderInstruction> program =
[
Load(0, 16),
Branch(4, "SCbranchScc0", 1),
Load(8, 16),
Nop(12),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrReachingState.Multiple, ssa.GetReachingDefinitionAt(12, 16).State);
}
[Fact]
public void DefinitionBeforeTheBranchStaysSingle()
{
List<Gen5ShaderInstruction> program =
[
Load(0, 16),
Branch(4, "SCbranchScc0", 1),
Load(8, 16),
Nop(12),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var reaching = ssa.GetReachingDefinitionAt(4, 16);
Assert.Equal(IrReachingState.Single, reaching.State);
Assert.Equal(0u, reaching.DefinitionPc);
}
[Fact]
public void UserDataCountsAsADefinition()
{
List<Gen5ShaderInstruction> program = [Nop(0)];
var ssa = Gen5ScalarSsa.Build(program, userData: [0x1111, 0x2222]);
Assert.Equal(IrReachingState.Single, ssa.GetReachingDefinitionAt(0, 0).State);
Assert.Equal(IrReachingState.None, ssa.GetReachingDefinitionAt(0, 64).State);
}
[Fact]
public void UnwrittenRegisterHasNoDefinition()
{
List<Gen5ShaderInstruction> program = [Load(0, 16), Nop(4)];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrReachingState.None, ssa.GetReachingDefinitionAt(4, 32).State);
}
[Fact]
public void ReachingDefinitionSeesLoadsThatConstantPropagationCannot()
{
// The whole point of the second analysis: SLoadDwordx4 has no compile-time
// value, so constant propagation reports Unknown and never Merged. Reaching
// definitions still proves the register has two possible writers.
List<Gen5ShaderInstruction> program =
[
Branch(0, "SCbranchScc0", 2),
Load(4, 16),
Branch(8, "SBranch", 1),
Load(12, 16),
Nop(16),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrScalarState.Unknown, ssa.GetScalarAt(16, 16).State);
Assert.Equal(IrReachingState.Multiple, ssa.GetReachingDefinitionAt(16, 16).State);
}
}
@@ -0,0 +1,168 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Ir;
using Xunit;
namespace SharpEmu.ShaderCompiler.Tests;
public sealed class Gen5ScalarSsaTests
{
private static Gen5ShaderInstruction Mov(uint pc, uint destination, uint literal) =>
new(
pc,
Gen5ShaderEncoding.Sop1,
"SMov",
[0u],
[new Gen5Operand(Gen5OperandKind.LiteralConstant, literal)],
[Gen5Operand.Scalar(destination)],
null);
private static Gen5ShaderInstruction Nop(uint pc) =>
new(pc, Gen5ShaderEncoding.Sop1, "SNop", [0u], [], [], null);
private static Gen5ShaderInstruction Branch(uint pc, string opcode, short wordOffset) =>
new(
pc,
Gen5ShaderEncoding.Sopp,
opcode,
[unchecked((uint)(ushort)wordOffset)],
[],
[],
null);
[Fact]
public void StraightLineMovResolvesToAConstant()
{
List<Gen5ShaderInstruction> program =
[
Mov(0, destination: 8, literal: 0x1234),
Nop(4),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var value = ssa.GetScalarAt(4, 8);
Assert.Equal(IrScalarState.Constant, value.State);
Assert.Equal(0x1234u, value.Constant);
}
[Fact]
public void UserDataSeedsTheEntryState()
{
List<Gen5ShaderInstruction> program = [Nop(0)];
var ssa = Gen5ScalarSsa.Build(program, userData: [0x40F55240, 0x00000004]);
Assert.Equal(IrScalarState.Constant, ssa.GetScalarAt(0, 0).State);
Assert.Equal(0x40F55240u, ssa.GetScalarAt(0, 0).Constant);
Assert.Equal(0x00000004u, ssa.GetScalarAt(0, 1).Constant);
}
[Fact]
public void ConflictingValuesFromTwoPathsBecomeMerged()
{
// if (cc) s8 = 0xAAAA else s8 = 0xBBBB; use s8
List<Gen5ShaderInstruction> program =
[
Branch(0, "SCbranchScc0", 2),
Mov(4, destination: 8, literal: 0xAAAA),
Branch(8, "SBranch", 1),
Mov(12, destination: 8, literal: 0xBBBB),
Nop(16),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.True(ssa.Graph.HasControlFlow);
Assert.Equal(IrScalarState.Merged, ssa.GetScalarAt(16, 8).State);
}
[Fact]
public void SameValueOnBothPathsStaysResolved()
{
List<Gen5ShaderInstruction> program =
[
Branch(0, "SCbranchScc0", 2),
Mov(4, destination: 8, literal: 0xCAFE),
Branch(8, "SBranch", 1),
Mov(12, destination: 8, literal: 0xCAFE),
Nop(16),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var value = ssa.GetScalarAt(16, 8);
Assert.Equal(IrScalarState.Constant, value.State);
Assert.Equal(0xCAFEu, value.Constant);
}
[Fact]
public void RegisterWrittenOnOnlyOnePathIsMergedAtTheJoin()
{
List<Gen5ShaderInstruction> program =
[
Mov(0, destination: 8, literal: 0x1111),
Branch(4, "SCbranchScc0", 1),
Mov(8, destination: 8, literal: 0x2222),
Nop(12),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.Equal(IrScalarState.Merged, ssa.GetScalarAt(12, 8).State);
}
[Fact]
public void ValueBeforeTheBranchIsStillResolved()
{
List<Gen5ShaderInstruction> program =
[
Mov(0, destination: 8, literal: 0x1111),
Branch(4, "SCbranchScc0", 1),
Mov(8, destination: 8, literal: 0x2222),
Nop(12),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
var value = ssa.GetScalarAt(4, 8);
Assert.Equal(IrScalarState.Constant, value.State);
Assert.Equal(0x1111u, value.Constant);
}
[Fact]
public void MergeJoinIsReportedForDivergentBlocks()
{
List<Gen5ShaderInstruction> program =
[
Branch(0, "SCbranchScc0", 1),
Mov(4, destination: 8, literal: 1),
Nop(8),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.True(ssa.IsInsideDivergentMerge(8));
Assert.False(ssa.IsInsideDivergentMerge(0));
}
[Fact]
public void LoopDoesNotHangTheFixpoint()
{
List<Gen5ShaderInstruction> program =
[
Mov(0, destination: 8, literal: 1),
Nop(4),
Branch(8, "SCbranchScc1", -3),
Nop(12),
];
var ssa = Gen5ScalarSsa.Build(program, userData: []);
Assert.NotEmpty(ssa.Graph.LoopHeaders);
Assert.Equal(IrScalarState.Constant, ssa.GetScalarAt(12, 8).State);
}
}
@@ -0,0 +1,127 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Generic;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Ir;
using Xunit;
namespace SharpEmu.ShaderCompiler.Tests;
public sealed class IrControlFlowTests
{
private sealed class Resolver : IIrBranchResolver
{
public Dictionary<uint, (bool Conditional, uint Target)> Branches { get; } = [];
public bool IsBranch(Gen5ShaderInstruction instruction) =>
Branches.ContainsKey(instruction.Pc);
public bool IsConditional(Gen5ShaderInstruction instruction) =>
Branches.TryGetValue(instruction.Pc, out var branch) && branch.Conditional;
public bool TryGetBranchTarget(Gen5ShaderInstruction instruction, out uint targetPc)
{
if (Branches.TryGetValue(instruction.Pc, out var branch))
{
targetPc = branch.Target;
return true;
}
targetPc = 0;
return false;
}
}
private static Gen5ShaderInstruction Instruction(uint pc) =>
new(pc, Gen5ShaderEncoding.Sop1, "SMov", [], [], [], null);
private static List<Gen5ShaderInstruction> Straight(params uint[] pcs)
{
var list = new List<Gen5ShaderInstruction>();
foreach (var pc in pcs)
{
list.Add(Instruction(pc));
}
return list;
}
[Fact]
public void StraightLineCodeIsASingleBlock()
{
var instructions = Straight(0, 4, 8, 12);
var cfg = IrControlFlowGraph.Build(instructions, new Resolver());
Assert.Single(cfg.Blocks);
Assert.False(cfg.HasControlFlow);
Assert.Empty(cfg.LoopHeaders);
}
[Fact]
public void ConditionalBranchSplitsIntoThreeBlocks()
{
var instructions = Straight(0, 4, 8, 12, 16);
var resolver = new Resolver();
resolver.Branches[4] = (Conditional: true, Target: 12);
var cfg = IrControlFlowGraph.Build(instructions, resolver);
Assert.Equal(3, cfg.Blocks.Count);
Assert.True(cfg.HasControlFlow);
var entry = cfg.BlockByStartPc[0];
var fallthrough = cfg.BlockByStartPc[8];
var target = cfg.BlockByStartPc[12];
Assert.Contains(target, cfg.Successors[entry]);
Assert.Contains(fallthrough, cfg.Successors[entry]);
Assert.Contains(entry, cfg.Predecessors[target]);
}
[Fact]
public void UnconditionalBranchDoesNotFallThrough()
{
var instructions = Straight(0, 4, 8, 12);
var resolver = new Resolver();
resolver.Branches[4] = (Conditional: false, Target: 12);
var cfg = IrControlFlowGraph.Build(instructions, resolver);
var entry = cfg.BlockByStartPc[0];
var skipped = cfg.BlockByStartPc[8];
var target = cfg.BlockByStartPc[12];
Assert.Equal([target], cfg.Successors[entry]);
Assert.DoesNotContain(skipped, cfg.Successors[entry]);
}
[Fact]
public void BackwardBranchMarksALoopHeader()
{
var instructions = Straight(0, 4, 8, 12);
var resolver = new Resolver();
resolver.Branches[8] = (Conditional: true, Target: 4);
var cfg = IrControlFlowGraph.Build(instructions, resolver);
var header = cfg.BlockByStartPc[4];
Assert.Contains(header, cfg.LoopHeaders);
Assert.Contains(header, cfg.Successors[cfg.BlockByStartPc[4]]);
}
[Fact]
public void MergeBlockRecordsBothPredecessors()
{
var instructions = Straight(0, 4, 8, 12, 16, 20);
var resolver = new Resolver();
resolver.Branches[0] = (Conditional: true, Target: 12);
resolver.Branches[8] = (Conditional: false, Target: 16);
var cfg = IrControlFlowGraph.Build(instructions, resolver);
var merge = cfg.BlockByStartPc[16];
Assert.Equal(2, cfg.Predecessors[merge].Count);
}
}