Compare commits

..

4 Commits

Author SHA1 Message Date
PJB3005
b422d3fb3e Version: 237.2.2 2025-09-19 09:17:39 +02:00
Skye
e4101aae8b Fix resource loading on non-Windows platforms (#6201)
(cherry picked from commit 51bbc5dc45)
2025-09-19 09:17:39 +02:00
PJB3005
74fe177985 Version: 237.2.1 2025-09-14 14:58:28 +02:00
PJB3005
bb90d79a3f Squashed commit of the following:
commit d4f265c314
Author: PJB3005 <pieterjan.briers+git@gmail.com>
Date:   Sun Sep 14 14:32:44 2025 +0200

    Fix incorrect path combine in DirLoader and WritableDirProvider

    This (and the other couple past commits) reported by Elelzedel.

commit 7654d38612
Author: PJB3005 <pieterjan.briers+git@gmail.com>
Date:   Sat Sep 13 22:50:51 2025 +0200

    Move CEF cache out of data directory

    Don't want content messing with this...

commit cdcc255123
Author: PJB3005 <pieterjan.briers+git@gmail.com>
Date:   Sat Sep 13 19:11:16 2025 +0200

    Make Robust.Client.WebView.Cef.Program internal.

commit 2f56a6a110
Author: PJB3005 <pieterjan.briers+git@gmail.com>
Date:   Sat Sep 13 19:10:46 2025 +0200

    Update SpaceWizards.NFluidSynth to 0.2.2

commit 16fc48cef2
Author: PJB3005 <pieterjan.briers+git@gmail.com>
Date:   Sat Sep 13 19:09:43 2025 +0200

    Hide IWritableDirProvider.RootDir on client

    This shouldn't be exposed.

(cherry picked from commit 2f07159336bc640e41fbbccfdec4133a68c13bdb)
(cherry picked from commit d6c3212c74373ed2420cc4be2cf10fcd899c2106)
(cherry picked from commit bfa70d7e2ca6758901b680547fcfa9b24e0610b7)
(cherry picked from commit 06e52f5d58efc1491915822c2650f922673c82c6)
(cherry picked from commit 4413695c77fb705054c2f81fa18ec0a189b685dd)
2025-09-14 14:58:27 +02:00
389 changed files with 15657 additions and 22960 deletions

View File

@@ -5,30 +5,30 @@ on:
- cron: "0 0 * * 0"
jobs:
docfx:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
with:
submodules: true
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3.6.0
with:
submodules: true
- name: Setup .NET Core
uses: actions/setup-dotnet@v4.1.0
with:
dotnet-version: 9.0.x
- name: Setup .NET Core
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: 8.0.x
- name: Install dependencies
run: dotnet restore
- name: Install dependencies
run: dotnet restore
- name: Build Project
run: dotnet build --no-restore /p:WarningsAsErrors=nullable
- name: Build Project
run: dotnet build --no-restore /p:WarningsAsErrors=nullable
- name: Build DocFX
uses: nikeee/docfx-action@v1.0.0
with:
args: Robust.Docfx/docfx.json
- name: Build DocFX
uses: nikeee/docfx-action@v1.0.0
with:
args: Robust.Docfx/docfx.json
- name: Publish Docfx Documentation on GitHub Pages
uses: maxheld83/ghpages@master
env:
BUILD_DIR: Robust.Docfx/_robust-site
GH_PAT: ${{ secrets.GH_PAT }}
- name: Publish Docfx Documentation on GitHub Pages
uses: maxheld83/ghpages@master
env:
BUILD_DIR: Robust.Docfx/_robust-site
GH_PAT: ${{ secrets.GH_PAT }}

View File

@@ -2,32 +2,33 @@ name: Build & Test
on:
push:
branches: [master]
branches: [ master ]
pull_request:
branches: [master]
branches: [ master ]
jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, windows-latest] # , macos-latest] - temporarily disabled due to libfreetype.dll errors.
os: [ubuntu-latest, windows-latest ] # , macos-latest] - temporarily disabled due to libfreetype.dll errors.
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4.2.2
with:
submodules: true
- uses: actions/checkout@v3.6.0
with:
submodules: true
- name: Setup .NET Core
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: 8.0.x
- name: Install dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore /p:WarningsAsErrors=nullable
- name: Robust.UnitTesting
run: dotnet test --no-build Robust.UnitTesting/Robust.UnitTesting.csproj -- NUnit.ConsoleOut=0
- name: Robust.Analyzers.Tests
run: dotnet test --no-build Robust.Analyzers.Tests/Robust.Analyzers.Tests.csproj -- NUnit.ConsoleOut=0
- name: Setup .NET Core
uses: actions/setup-dotnet@v4.1.0
with:
dotnet-version: 9.0.x
- name: Install dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore /p:WarningsAsErrors=nullable
- name: Robust.UnitTesting
run: dotnet test --no-build Robust.UnitTesting/Robust.UnitTesting.csproj -- NUnit.ConsoleOut=0
- name: Robust.Analyzers.Tests
run: dotnet test --no-build Robust.Analyzers.Tests/Robust.Analyzers.Tests.csproj -- NUnit.ConsoleOut=0

View File

@@ -11,8 +11,14 @@
#
name: "CodeQL"
on:
workflow_dispatch
#on:
# push:
# branches: [ master ]
# pull_request:
# # The branches below must be a subset of the branches above
# branches: [ master ]
# schedule:
# - cron: '30 18 * * 6'
jobs:
analyze:
@@ -22,50 +28,50 @@ jobs:
strategy:
fail-fast: false
matrix:
language: ["csharp"]
language: [ 'csharp' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v4.2.2
with:
submodules: true
- name: Checkout repository
uses: actions/checkout@v3.6.0
with:
submodules: true
- name: Setup .NET Core
uses: actions/setup-dotnet@v4.1.0
with:
dotnet-version: 7.0.x
- name: Setup .NET Core
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: 7.0.x
- name: Build
run: dotnet build
- name: Build
run: dotnet build
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@@ -3,50 +3,51 @@
on:
push:
tags:
- "v*"
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Parse version
id: parse_version
shell: pwsh
run: |
$ver = [regex]::Match($env:GITHUB_REF, "refs/tags/v?(.+)").Groups[1].Value
echo ("::set-output name=version::{0}" -f $ver)
- name: Parse version
id: parse_version
shell: pwsh
run: |
$ver = [regex]::Match($env:GITHUB_REF, "refs/tags/v?(.+)").Groups[1].Value
echo ("::set-output name=version::{0}" -f $ver)
- uses: actions/checkout@v4.2.2
with:
submodules: true
- uses: actions/checkout@v3.6.0
with:
submodules: true
- name: Setup .NET Core
uses: actions/setup-dotnet@v4.1.0
with:
dotnet-version: 9.0.x
- name: Setup .NET Core
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: 8.0.x
- name: Package client
run: Tools/package_client_build.py -p windows mac linux
- name: Package client
run: Tools/package_client_build.py -p windows mac linux
- name: Shuffle files around
run: |
mkdir "release/${{ steps.parse_version.outputs.version }}"
mv release/*.zip "release/${{ steps.parse_version.outputs.version }}"
- name: Shuffle files around
run: |
mkdir "release/${{ steps.parse_version.outputs.version }}"
mv release/*.zip "release/${{ steps.parse_version.outputs.version }}"
- name: Upload files to Suns
uses: appleboy/scp-action@master
with:
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
source: "release/${{ steps.parse_version.outputs.version }}"
target: "/var/lib/robust-builds/builds/"
strip_components: 1
- name: Upload files to Suns
uses: appleboy/scp-action@master
with:
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
source: "release/${{ steps.parse_version.outputs.version }}"
target: "/var/lib/robust-builds/builds/"
strip_components: 1
- name: Update manifest JSON
uses: appleboy/ssh-action@master
with:
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
script: /home/robust-build-push/push.ps1 ${{ steps.parse_version.outputs.version }}
- name: Update manifest JSON
uses: appleboy/ssh-action@master
with:
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
script: /home/robust-build-push/push.ps1 ${{ steps.parse_version.outputs.version }}

View File

@@ -2,39 +2,40 @@ name: Test content master against engine
on:
push:
branches: [master]
branches: [ master ]
pull_request:
branches: [master]
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out content
uses: actions/checkout@v4.2.2
with:
repository: space-wizards/space-station-14
submodules: recursive
- name: Check out content
uses: actions/checkout@v3.6.0
with:
repository: space-wizards/space-station-14
submodules: recursive
- name: Setup .NET Core
uses: actions/setup-dotnet@v4.1.0
with:
dotnet-version: 9.0.x
- name: Disable submodule autoupdate
run: touch BuildChecker/DISABLE_SUBMODULE_AUTOUPDATE
- name: Setup .NET Core
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: 8.0.x
- name: Disable submodule autoupdate
run: touch BuildChecker/DISABLE_SUBMODULE_AUTOUPDATE
- name: Check out engine version
run: |
cd RobustToolbox
git fetch origin ${{ github.sha }}
git checkout FETCH_HEAD
git submodule update --init --recursive
- name: Install dependencies
run: dotnet restore
- name: Build
run: dotnet build --configuration Tools --no-restore
- name: Content.Tests
run: dotnet test --no-build Content.Tests/Content.Tests.csproj -v n
- name: Content.IntegrationTests
run: COMPlus_gcServer=1 dotnet test --no-build Content.IntegrationTests/Content.IntegrationTests.csproj -v n
- name: Check out engine version
run: |
cd RobustToolbox
git fetch origin ${{ github.sha }}
git checkout FETCH_HEAD
git submodule update --init --recursive
- name: Install dependencies
run: dotnet restore
- name: Build
run: dotnet build --configuration Tools --no-restore
- name: Content.Tests
run: dotnet test --no-build Content.Tests/Content.Tests.csproj -v n
- name: Content.IntegrationTests
run: COMPlus_gcServer=1 dotnet test --no-build Content.IntegrationTests/Content.IntegrationTests.csproj -v n

View File

@@ -10,69 +10,66 @@
<ManagePackageVersionsCentrally />
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="BenchmarkDotNet" Version="0.14.0" />
<PackageVersion Include="BenchmarkDotNet" Version="0.13.12" />
<PackageVersion Include="DiscordRichPresence" Version="1.2.1.24" />
<PackageVersion Include="JetBrains.Annotations" Version="2024.3.0" />
<PackageVersion Include="JetBrains.Profiler.Api" Version="1.4.8" />
<PackageVersion Include="ILReader.Core" Version="1.0.0.4" />
<PackageVersion Include="JetBrains.Annotations" Version="2023.3.0" />
<PackageVersion Include="JetBrains.Profiler.Api" Version="1.4.0" />
<PackageVersion Include="Linguini.Bundle" Version="0.8.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzer.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Features" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Common" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.Common" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeCoverage" Version="17.12.0" />
<PackageVersion Include="Microsoft.Data.Sqlite.Core" Version="9.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzer.Testing" Version="1.1.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.NUnit" Version="1.1.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.NUnit" Version="1.1.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Features" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Common" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.Common" Version="4.8.0" />
<PackageVersion Include="Microsoft.CodeCoverage" Version="17.8.0" />
<PackageVersion Include="Microsoft.Data.Sqlite.Core" Version="8.0.0" />
<PackageVersion Include="Microsoft.DotNet.RemoteExecutor" Version="8.0.0-beta.24059.4" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Primitives" Version="9.0.0" />
<PackageVersion Include="Microsoft.ILVerification" Version="9.0.0" />
<PackageVersion Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
<PackageVersion Include="Microsoft.NET.ILLink.Tasks" Version="9.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageVersion Include="Microsoft.ILVerification" Version="8.0.0" />
<PackageVersion Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.0" />
<PackageVersion Include="Microsoft.NET.ILLink.Tasks" Version="8.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageVersion Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="NUnit" Version="4.3.2" />
<PackageVersion Include="NUnit.Analyzers" Version="4.5.0" />
<PackageVersion Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageVersion Include="Moq" Version="4.20.70" />
<PackageVersion Include="NUnit" Version="4.0.1" />
<PackageVersion Include="NUnit.Analyzers" Version="3.10.0" />
<PackageVersion Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageVersion Include="Nett" Version="0.15.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.2" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageVersion Include="OpenTK.OpenAL" Version="4.7.7" />
<PackageVersion Include="OpenToolkit.Graphics" Version="4.0.0-pre9.1" />
<PackageVersion Include="Pidgin" Version="3.3.0" />
<PackageVersion Include="Pidgin" Version="3.2.2" />
<PackageVersion Include="Robust.Natives" Version="0.1.1" />
<PackageVersion Include="Robust.Natives.Cef" Version="131.3.5" />
<PackageVersion Include="Robust.Natives.Cef" Version="120.1.9" />
<PackageVersion Include="Robust.Shared.AuthLib" Version="0.1.2" />
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.10" />
<PackageVersion Include="SQLitePCLRaw.provider.sqlite3" Version="2.1.10" />
<PackageVersion Include="Serilog" Version="4.2.0" />
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.7" />
<PackageVersion Include="SQLitePCLRaw.provider.sqlite3" Version="2.1.7" />
<PackageVersion Include="Serilog" Version="3.1.1" />
<PackageVersion Include="Serilog.Sinks.Loki" Version="4.0.0-beta3" />
<PackageVersion Include="SharpZstd.Interop" Version="1.5.2-beta2" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.6" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageVersion Include="SpaceWizards.HttpListener" Version="0.1.1" />
<PackageVersion Include="SpaceWizards.NFluidsynth" Version="0.1.1" />
<PackageVersion Include="SpaceWizards.NFluidsynth" Version="0.2.2" />
<PackageVersion Include="SpaceWizards.SharpFont" Version="1.0.2" />
<PackageVersion Include="SpaceWizards.Sodium" Version="0.2.1" />
<PackageVersion Include="TerraFX.Interop.Windows" Version="10.0.26100.1" />
<PackageVersion Include="System.Numerics.Vectors" Version="4.5.0" />
<PackageVersion Include="System.Memory" Version="4.5.5" />
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageVersion Include="TerraFX.Interop.Windows" Version="10.0.22621.5" />
<PackageVersion Include="TerraFX.Interop.Xlib" Version="6.4.0" />
<PackageVersion Include="VorbisPizza" Version="1.3.0" />
<PackageVersion Include="YamlDotNet" Version="16.3.0" />
<PackageVersion Include="YamlDotNet" Version="13.7.1" />
<PackageVersion Include="prometheus-net" Version="8.2.1" />
<PackageVersion Include="prometheus-net.DotNetRuntime" Version="4.4.0" />
<PackageVersion Include="PolySharp" Version="1.15.0" />
<!-- Transitive deps that we need to pin versions for to avoid NuGet warnings. -->
<PackageVersion Include="System.Formats.Asn1" Version="9.0.0" />
<PackageVersion Include="System.Reflection.Metadata" Version="9.0.0" />
<PackageVersion Include="System.Text.Json" Version="9.0.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.12.0" />
<PackageVersion Include="PolySharp" Version="1.14.1" />
</ItemGroup>
</Project>

View File

@@ -12,7 +12,7 @@
<SkipRobustAnalyzer>true</SkipRobustAnalyzer>
<Nullable>enable</Nullable>
<LangVersion>13.0</LangVersion>
<LangVersion>12.0</LangVersion>
</PropertyGroup>
<ItemGroup>

View File

@@ -1,4 +1,4 @@
<Project>
<!-- This file automatically reset by Tools/version.py -->
<!-- This file automatically reset by Tools/version.py -->

View File

@@ -1,8 +1,8 @@
<Project>
<!-- Engine-specific properties. Content should not use this file. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>13</LangVersion>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>12</LangVersion>
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>

View File

@@ -3,7 +3,7 @@
<!-- Import this at the end of any project files in Robust and Content. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>

View File

@@ -1,4 +1,4 @@
# Release notes for RobustToolbox.
# Release notes for RobustToolbox.
<!--
NOTE: automatically updated sometimes by version.py.
@@ -54,261 +54,10 @@ END TEMPLATE-->
*None yet*
## 245.0.0
## 237.2.2
### Breaking changes
* `BoundUserInterface.Open()` now has the `MustCallBase` attribute
### Bugfixes
* Fixed an error in `MappingDataNode.TryAddCopy()`, which was causing yaml inheritance/deserialization bugs.
## 244.0.0
### Breaking changes
* Increase physics speedcap default from 35m/s to 400m/s in-line with box2d v3.
### New features
* Add EntityManager overloads for ComponentRegistration that's faster than the generic methods.
* Add CreateWindowCenteredRight for BUIs.
### Bugfixes
* Avoid calling UpdateState before opening a BUI.
## 243.0.1
### Bugfixes
* Fixed `BaseWindow` sometimes not properly updating the mouse cursor shape.
* Revert `BaseWindow` OnClose ordering due to prior reliance upon the ordering.
## 243.0.0
### Breaking changes
* RemoveChild is called after OnClose for BaseWindow.
### New features
* BUIs now have their positions saved when closed and re-used when opened when using the `CreateWindow<T>` helper or via manually registering it via RegisterControl.
### Other
* Ensure grid fixtures get updated in client state handling even if exceptions occur.
## 242.0.1
### Bugfixes
* Fixed prototype reloading/hotloading not properly handling data-fields with the `AlwaysPushInheritanceAttribute`
* Fix the pooled polygons using incorrect vertices for EntityLookup and MapManager.
### Internal
* Avoid normalizing angles constructed from vectors.
## 242.0.0
### Breaking changes
* The order in which the client initialises networked entities has changed. It will now always apply component states, initialise, and start an entity's parent before processing any children. This might break anything that was relying on the old behaviour where all component states were applied before any entities were initialised & started.
* `IClydeViewport` overlay rendering methods now take in an `IRenderHandle` instead of a world/screen handle.
* The `OverlayDrawArgs` struct now has an internal constructor.
### New features
* Controls can now be manually restyled via `Control.InvalidateStyleSheet()` and `Control.DoStyleUpdate()`
* Added `IUserInterfaceManager.RenderControl()` for manually drawing controls.
* `OverlayDrawArgs` struct now has an `IRenderHandle` field such that overlays can use the new `RenderControl()` methods.
* TileSpawnWindow will now take focus when opened.
### Bugfixes
* Fixed a client-side bug where `TransformComponent.GridUid` does not get set properly when an existing entity is attached to a new entity outside of the player's PVS range.
* EntityPrototypeView will only create entities when it's on the UI tree and not when the prototype is set.
* Make CollisionWake not log errors if it can't resolve.
### Other
* Replace IPhysShape API with generics on IMapManager and EntityLookupSystem.
### Internal
* Significantly reduce allocations for Box2 / Box2Rotated queries.
## 241.0.0
### Breaking changes
* Remove DeferredClose from BUIs.
### New features
* Added `EntityManager.DirtyFields()`, which allows components with delta states to simultaneously mark several fields as dirty at the same time.
* Add `CloserUserUIs<T>` to close keys of a specific key.
### Bugfixes
* Fixed `RaisePredictiveEvent()` not properly re-raising events during prediction for event handlers that did not take an `EntitySessionEventArgs` argument.
* BUI openings are now deferred to avoid having slight desync between deferred closes and opens occurring in the same tick.
## 240.1.2
## 240.1.1
### Bugfixes
* Fixed one of the `IOverlayManager.RemoveOverlay` overrides not fully removing the overlay.
## 240.1.0
### New features
* Added an `AsNullable` extension method for converting an `Entity<T>` into an `Entity<T?>`
### Bugfixes
* Fixed an exception in `PhysicsSystem.DestroyContacts()` that could result in entities getting stuck with broken physics.
### Other
* `GamePrototypeLoadManager` will now send all uploaded prototypes to connecting players in a single `GamePrototypeLoadMessage`, as opposed to one message per upload.
## 240.0.1
### Bugfixes
* Fixed `SharedBroadphaseSystem.GetBroadphases()` not returning the map itself, which was causing physics to not work properly off-grid.
## 240.0.0
### Breaking changes
* `ComponentRegistry` no longer implements `ISerializationContext`
* Tickrate values are now `ushort`, allowing them to go up to 65535.
### New features
* Console completion options now have new flags for preventing suggestions from being escaped or quoted.
* Added `ILocalizationManager.HasCulture()`.
* Static `EntProtoId<T>` fields are now validated to exist.
### Bugfixes
* Fixed a state handling bug in replays, which was causing exceptions to be thrown when applying delta states.
### Other
* Reduced amount of `DynamicMethod`s used by serialization system. This should improve performance somewhat.
### Internal
* Avoided sorting overlays every render frame.
* Various clean up to grid fixture code/adding asserts.
## 239.0.1
### Bugfixes
* Fix logging of received packets with `net.packet` logging level.
* Downgrade `VorbisPizza` to fix audio playback for systems without AVX2 support.
### Other
* Improved performance of some Roslyn analyzers and source generators, which should significantly improve compile times and IDE performance.
## 239.0.0
### Breaking changes
* Robust now uses **.NET 9**.
* `ISerializationManager` will now log errors if it encounters `Entity<T>` data-fields.
* To be clear, this has never been supported and is not really a breaking change, but this will likely require manual intervention to prevent tests from failing.
* `IClyde.TextInputSetRect`, `TextInputStart` and `TextInputStop` have been moved to be on `IClydeWindow`.
* Updated various NuGet dependencies and removed some other ones, of note:
* `FastAccessors`, which is a transitive dep we never used, is now gone. It might have snuck into some `using` statement thanks to your IDE, and those will now fail to compile. Remove them.
* NUnit `Is.EqualTo(default)` seems to have ambiguous overload resolution in some cases now, this can be fixed by using an explicit `default(type)` syntax.
* This also fixed various false-positive warnings reported by NuGet.
### New features
* Added `MockInterfaces.MakeConfigurationManager` for creating functional configuration managers for unit test mocking.
* Added `ISawmill.IsLogLevelEnabled()` to avoid doing expensive verbose logging operations when not necessary.
* ``string[] Split(System.ReadOnlySpan`1<char>)`` is now available in sandbox.
### Bugfixes
* Fixed auto-generated component delta-states not raising `AfterAutoHandleStateEvent`
* Fixed auto-generated component delta-states improperly implementing `IComponentDeltaState` methods. May have caused bugs in replays.
* Fixed `Robust.Client.WebView` on the launcher via a new release.
* Fixed an exception that could occur when saving a map that had tiles migrated by alias.
### Other
* The `loglevel` command now properly shows the "`null`" log level that resets the level to inheriting from parent. This was already supported by it, but the completions didn't list it.
### Internal
* Experimental SDL2 windowing backend has been replaced with SDL3. SDL3 backend is also more feature-complete, though it is still not in use.
* Updated CEF used by Robust.Client.WebView to 131.3.5.
## 238.0.1
### Bugfixes
* Fixed source generation for auto-networked EntityUid Dictionaries missing a semicolon
* Fixed PlacementManager using the wrong coordinates when deleting entities in an area.
## 238.0.0
### Breaking changes
* Some toolshed command syntax/parsing has changed slightly, and several toolshed related classes and interfaces have changed significantly, including ToolshedManager, type parsers, invocation contexts, and parser contexts. For more detail see the the description of PR #5455
## 237.4.0
### New features
* Implement automatic field-level delta states via AutoGenerateComponentState via opt-in.
### Bugfixes
* Remove redundant TransformComponentState bool.
## 237.3.0
### New features
* Added stack-like functions to `ValueList<T>` and added an `AddRange(ReadOnlySpan<T>)` overload.
* Added new `AssetPassFilterDrop`.
* Added a new RayCastSystem with the latest Box2D raycast + shapecasts implemented.
### Bugfixes
* Fixed `IPrototypeManager.TryGetKindFrom()` not working for prototypes with automatically inferred kind names.
### Other
* Sandbox error reference locator now works with generic method calls.
## 237.2.1
## 237.2.0

View File

@@ -1,8 +1,4 @@
command-help-usage =
Usage:
command-help-invertible =
The behaviour of this command can be inverted using the "not" prefix.
command-description-tpto =
command-description-tpto =
Teleport the given entities to some target entity.
command-description-player-list =
Returns a list of all player sessions.
@@ -23,7 +19,7 @@ command-description-buildinfo =
command-description-cmd-list =
Returns a list of all commands, for this side.
command-description-explain =
Explains the given expression, providing command descriptions and signatures. This only works for valid expressions, it can't explain commands that it fails to parse.
Explains the given expression, providing command descriptions and signatures.
command-description-search =
Searches through the input for the provided value.
command-description-stopwatch =
@@ -57,8 +53,10 @@ command-description-entities =
Returns all entities on the server.
command-description-paused =
Filters the input entities by whether or not they are paused.
This command can be inverted with not.
command-description-with =
Filters the input entities by whether or not they have the given component.
This command can be inverted with not.
command-description-fuck =
Throws an exception.
command-description-ecscomp-listty =
@@ -97,8 +95,6 @@ command-description-vars =
Provides a list of all variables set in this session.
command-description-any =
Returns true if there's any values in the input, otherwise false.
command-description-contains =
Returns whether the input enumerable contains the specified value.
command-description-ArrowCommand =
Assigns the input to a variable.
command-description-isempty =
@@ -123,8 +119,6 @@ command-description-splat =
"Splats" a block, value, or variable, creating N copies of it in a list.
command-description-val =
Casts the given value, block, or variable to the given type. This is mostly a workaround for current limitations of variables.
command-description-var =
Returns the contents of the given variable. This will attempt to automatically infer a variables type. Compound commands that modify a variable may need to use the 'val' command instead.
command-description-actor-controlled =
Filters entities by whether or not they're actively controlled.
command-description-actor-session =

View File

@@ -1,8 +1,12 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS = Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.AccessAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
using Robust.Analyzers;
using VerifyCS = Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.AccessAnalyzer>;
using static Microsoft.CodeAnalysis.Testing.DiagnosticResult;
namespace Robust.Analyzers.Tests;
@@ -12,7 +16,7 @@ public sealed class AccessAnalyzer_Test
{
public Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<AccessAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<AccessAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,114 +0,0 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.ByRefEventAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
namespace Robust.Analyzers.Tests;
[Parallelizable(ParallelScope.All | ParallelScope.Fixtures)]
[TestFixture, TestOf(typeof(ByRefEventAnalyzer))]
public sealed class ByRefEventAnalyzerTest
{
private const string EventBusDef = """
namespace Robust.Shared.GameObjects;
public readonly struct EntityUid;
public sealed class EntitySystem
{
public void RaiseLocalEvent<TEvent>(EntityUid uid, ref TEvent args, bool broadcast = false)
where TEvent : notnull { }
public void RaiseLocalEvent<TEvent>(EntityUid uid, TEvent args, bool broadcast = false)
where TEvent : notnull { }
}
public sealed class EntityEventBus
{
public void RaiseLocalEvent<TEvent>(EntityUid uid, ref TEvent args, bool broadcast = false)
where TEvent : notnull { }
public void RaiseLocalEvent<TEvent>(EntityUid uid, TEvent args, bool broadcast = false)
where TEvent : notnull { }
}
""";
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<ByRefEventAnalyzer, DefaultVerifier>()
{
TestState =
{
Sources = { code }
},
};
TestHelper.AddEmbeddedSources(
test.TestState,
"Robust.Shared.GameObjects.EventBusAttributes.cs"
);
test.TestState.Sources.Add(("EntityEventBus.cs", EventBusDef));
// ExpectedDiagnostics cannot be set, so we need to AddRange here...
test.TestState.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync();
}
[Test]
public async Task TestSuccess()
{
const string code = """
using Robust.Shared.GameObjects;
[ByRefEvent]
public readonly struct RefEvent;
public readonly struct ValueEvent;
public static class Foo
{
public static void Bar(EntityEventBus bus)
{
bus.RaiseLocalEvent(default(EntityUid), new ValueEvent());
var refEv = new RefEvent();
bus.RaiseLocalEvent(default(EntityUid), ref refEv);
}
}
""";
await Verifier(code);
}
[Test]
public async Task TestWrong()
{
const string code = """
using Robust.Shared.GameObjects;
[ByRefEvent]
public readonly struct RefEvent;
public readonly struct ValueEvent;
public static class Foo
{
public static void Bar(EntityEventBus bus)
{
bus.RaiseLocalEvent(default(EntityUid), new RefEvent());
var valueEv = new ValueEvent();
bus.RaiseLocalEvent(default(EntityUid), ref valueEv);
}
}
""";
await Verifier(
code,
// /0/Test0.cs(11,49): error RA0015: Tried to raise a by-ref event 'RefEvent' by value
VerifyCS.Diagnostic(ByRefEventAnalyzer.ByRefEventRaisedByValueRule).WithSpan(11, 49, 11, 63).WithArguments("RefEvent"),
// /0/Test0.cs(13,49): error RA0016: Tried to raise a value event 'ValueEvent' by-ref
VerifyCS.Diagnostic(ByRefEventAnalyzer.ByValueEventRaisedByRefRule).WithSpan(13, 49, 13, 60).WithArguments("ValueEvent")
);
}
}

View File

@@ -66,7 +66,6 @@ public sealed class ComponentPauseGeneratorTest
public partial class FooComponent
{
[RobustAutoGenerated]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
public sealed class FooComponent_AutoPauseSystem : EntitySystem
{
public override void Initialize()
@@ -107,7 +106,6 @@ public sealed class ComponentPauseGeneratorTest
public partial class FooComponent
{
[RobustAutoGenerated]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
public sealed class FooComponent_AutoPauseSystem : EntitySystem
{
public override void Initialize()
@@ -149,7 +147,6 @@ public sealed class ComponentPauseGeneratorTest
public partial class FooComponent
{
[RobustAutoGenerated]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
public sealed class FooComponent_AutoPauseSystem : EntitySystem
{
public override void Initialize()
@@ -191,7 +188,6 @@ public sealed class ComponentPauseGeneratorTest
public partial class FooComponent
{
[RobustAutoGenerated]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
public sealed class FooComponent_AutoPauseSystem : EntitySystem
{
public override void Initialize()

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.DataDefinitionAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.DataDefinitionAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class DataDefinitionAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<DataDefinitionAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<DataDefinitionAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.DependencyAssignAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.DependencyAssignAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class DependencyAssignAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<DependencyAssignAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<DependencyAssignAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.DuplicateDependencyAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.DuplicateDependencyAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -14,7 +15,7 @@ public sealed class DuplicateDependencyAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<DuplicateDependencyAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<DuplicateDependencyAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.MustCallBaseAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.MustCallBaseAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class MustCallBaseAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<MustCallBaseAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<MustCallBaseAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.NoUncachedRegexAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.NoUncachedRegexAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class NoUncachedRegexAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<NoUncachedRegexAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<NoUncachedRegexAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.PreferNonGenericVariantForAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.PreferNonGenericVariantForAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class PreferNonGenericVariantForTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<PreferNonGenericVariantForAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<PreferNonGenericVariantForAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.PreferOtherTypeAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.PreferOtherTypeAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -13,7 +14,7 @@ public sealed class PreferOtherTypeAnalyzerTest
{
private static Task Verifier(string code, params DiagnosticResult[] expected)
{
var test = new CSharpAnalyzerTest<PreferOtherTypeAnalyzer, DefaultVerifier>()
var test = new CSharpAnalyzerTest<PreferOtherTypeAnalyzer, NUnitVerifier>()
{
TestState =
{

View File

@@ -1,9 +1,10 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using NUnit.Framework;
using VerifyCS =
Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<Robust.Analyzers.PreferOtherTypeAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.PreferOtherTypeAnalyzer>;
namespace Robust.Analyzers.Tests;
@@ -11,7 +12,7 @@ public sealed class PreferOtherTypeFixerTest
{
private static Task Verifier(string code, string fixedCode, params DiagnosticResult[] expected)
{
var test = new CSharpCodeFixTest<PreferOtherTypeAnalyzer, PreferOtherTypeFixer, DefaultVerifier>()
var test = new CSharpCodeFixTest<PreferOtherTypeAnalyzer, PreferOtherTypeFixer, NUnitVerifier>()
{
TestState =
{

View File

@@ -14,7 +14,6 @@
<EmbeddedResource Include="..\Robust.Shared\Analyzers\PreferNonGenericVariantForAttribute.cs" LogicalName="Robust.Shared.Analyzers.PreferNonGenericVariantForAttribute.cs" LinkBase="Implementations" />
<EmbeddedResource Include="..\Robust.Shared\Analyzers\PreferOtherTypeAttribute.cs" LogicalName="Robust.Shared.Analyzers.PreferOtherTypeAttribute.cs" LinkBase="Implementations" />
<EmbeddedResource Include="..\Robust.Shared\IoC\DependencyAttribute.cs" LogicalName="Robust.Shared.IoC.DependencyAttribute.cs" LinkBase="Implementations" />
<EmbeddedResource Include="..\Robust.Shared\GameObjects\EventBusAttributes.cs" LogicalName="Robust.Shared.GameObjects.EventBusAttributes.cs" LinkBase="Implementations" />
</ItemGroup>
<PropertyGroup>
@@ -28,17 +27,13 @@
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzer.Testing"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.NUnit"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.NUnit"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces"/>
<PackageReference Include="NUnit"/>
<PackageReference Include="NUnit3TestAdapter"/>
<PackageReference Include="NUnit.Analyzers"/>
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<!-- Needed to fix transitive dependency versions -->
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.Common" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
<PackageReference Include="System.Formats.Asn1" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,4 +1,4 @@
#nullable enable
#nullable enable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
@@ -24,7 +24,7 @@ public sealed class ByRefEventAnalyzer : DiagnosticAnalyzer
"Make sure that methods subscribing to a ref event have the ref keyword for the event argument."
);
public static readonly DiagnosticDescriptor ByRefEventRaisedByValueRule = new(
private static readonly DiagnosticDescriptor ByRefEventRaisedByValueRule = new(
Diagnostics.IdByRefEventRaisedByValue,
"By-ref event raised by value",
"Tried to raise a by-ref event '{0}' by value",
@@ -34,7 +34,7 @@ public sealed class ByRefEventAnalyzer : DiagnosticAnalyzer
"Make sure to use the ref keyword when raising ref events."
);
public static readonly DiagnosticDescriptor ByValueEventRaisedByRefRule = new(
private static readonly DiagnosticDescriptor ByValueEventRaisedByRefRule = new(
Diagnostics.IdValueEventRaisedByRef,
"Value event raised by-ref",
"Tried to raise a value event '{0}' by-ref",
@@ -54,44 +54,32 @@ public sealed class ByRefEventAnalyzer : DiagnosticAnalyzer
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(compilationContext =>
{
var raiseMethods = compilationContext.Compilation
.GetTypeByMetadataName("Robust.Shared.GameObjects.EntitySystem")?
.GetMembers()
.Where(m => m.Name.Contains("RaiseLocalEvent") && m.Kind == SymbolKind.Method)
.Cast<IMethodSymbol>();
var busRaiseMethods = compilationContext.Compilation
.GetTypeByMetadataName("Robust.Shared.GameObjects.EntityEventBus")?
.GetMembers()
.Where(m => m.Name.Contains("RaiseLocalEvent") && m.Kind == SymbolKind.Method)
.Cast<IMethodSymbol>();
if (raiseMethods == null)
return;
if (busRaiseMethods != null)
raiseMethods = raiseMethods.Concat(busRaiseMethods);
var raiseMethodsArray = raiseMethods.ToArray();
compilationContext.RegisterOperationAction(
ctx => CheckEventRaise(ctx, raiseMethodsArray),
OperationKind.Invocation);
});
context.RegisterOperationAction(CheckEventRaise, OperationKind.Invocation);
}
private static void CheckEventRaise(
OperationAnalysisContext context,
IReadOnlyCollection<IMethodSymbol> raiseMethods)
private void CheckEventRaise(OperationAnalysisContext context)
{
if (context.Operation is not IInvocationOperation operation)
return;
if (!operation.TargetMethod.Name.Contains("RaiseLocalEvent"))
var raiseMethods = context.Compilation
.GetTypeByMetadataName("Robust.Shared.GameObjects.EntitySystem")?
.GetMembers()
.Where(m => m.Name.Contains("RaiseLocalEvent") && m.Kind == SymbolKind.Method)
.Cast<IMethodSymbol>();
var busRaiseMethods = context.Compilation
.GetTypeByMetadataName("Robust.Shared.GameObjects.EntityEventBus")?
.GetMembers()
.Where(m => m.Name.Contains("RaiseLocalEvent") && m.Kind == SymbolKind.Method)
.Cast<IMethodSymbol>();
if (raiseMethods == null)
return;
if (busRaiseMethods != null)
raiseMethods = raiseMethods.Concat(busRaiseMethods);
if (!raiseMethods.Any(m => m.Equals(operation.TargetMethod.OriginalDefinition, Default)))
{
// If you try to do this normally by concatenating like busRaiseMethods above

View File

@@ -1,96 +0,0 @@
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using JetBrains.Annotations;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.UnitTesting.Server;
namespace Robust.Benchmarks.EntityManager;
[Virtual]
public partial class HasComponentBenchmark
{
private static readonly Consumer Consumer = new();
private ISimulation _simulation = default!;
private IEntityManager _entityManager = default!;
private ComponentRegistration _compReg = default!;
private A _dummyA = new();
[UsedImplicitly]
[Params(1, 10, 100, 1000)]
public int N;
[GlobalSetup]
public void GlobalSetup()
{
_simulation = RobustServerSimulation
.NewSimulation()
.RegisterComponents(f => f.RegisterClass<A>())
.InitializeInstance();
_entityManager = _simulation.Resolve<IEntityManager>();
var map = _simulation.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);
_compReg = _entityManager.ComponentFactory.GetRegistration(typeof(A));
for (var i = 0; i < N; i++)
{
var uid = _entityManager.SpawnEntity(null, coords);
_entityManager.AddComponent<A>(uid);
}
}
[Benchmark]
public void HasComponentGeneric()
{
for (var i = 2; i <= N+1; i++)
{
var uid = new EntityUid(i);
var result = _entityManager.HasComponent<A>(uid);
Consumer.Consume(result);
}
}
[Benchmark]
public void HasComponentCompReg()
{
for (var i = 2; i <= N+1; i++)
{
var uid = new EntityUid(i);
var result = _entityManager.HasComponent(uid, _compReg);
Consumer.Consume(result);
}
}
[Benchmark]
public void HasComponentType()
{
for (var i = 2; i <= N+1; i++)
{
var uid = new EntityUid(i);
var result = _entityManager.HasComponent(uid, typeof(A));
Consumer.Consume(result);
}
}
[Benchmark]
public void HasComponentGetType()
{
for (var i = 2; i <= N+1; i++)
{
var uid = new EntityUid(i);
var type = _dummyA.GetType();
var result = _entityManager.HasComponent(uid, type);
Consumer.Consume(result);
}
}
[ComponentProtoName("A")]
public sealed partial class A : Component
{
}
}

View File

@@ -19,10 +19,6 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
<!-- Needed to pin transitive dependency versions. -->
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" />
<PackageReference Include="System.Formats.Asn1" />
</ItemGroup>
<Import Project="..\MSBuild\Robust.Properties.targets" />

View File

@@ -15,9 +15,6 @@ using XamlX.Transform;
using XamlX.Transform.Transformers;
using XamlX.TypeSystem;
// Yes dude I know this source generator isn't incremental, I'll fix it eventually.
#pragma warning disable RS1035
namespace Robust.Client.NameGenerator
{
/// <summary>

View File

@@ -64,8 +64,6 @@ internal abstract class BaseRobustCefClient : CefClient
string title,
string defaultFilePath,
string[] acceptFilters,
string[] acceptExtensions,
string[] acceptDescriptions,
CefFileDialogCallback callback)
{
callback.Cancel();

View File

@@ -6,7 +6,7 @@ using Xilium.CefGlue;
namespace Robust.Client.WebView.Cef
{
public static class Program
internal static class Program
{
// This was supposed to be the main entry for the subprocess program... It doesn't work.
public static int Main(string[] args)

View File

@@ -44,8 +44,6 @@ namespace Robust.Client.WebView.Cef
//commandLine.AppendSwitch("--disable-gpu-compositing");
//commandLine.AppendSwitch("--in-process-gpu");
commandLine.AppendSwitch("--off-screen-rendering-enabled");
commandLine.AppendSwitch("disable-threaded-scrolling", "1");
commandLine.AppendSwitch("disable-features", "TouchpadAndWheelScrollLatching,AsyncWheelEvents");

View File

@@ -23,7 +23,6 @@ namespace Robust.Client.WebView.Cef
var info = CefWindowInfo.Create();
info.Bounds = new CefRectangle(0, 0, createParams.Width, createParams.Height);
info.SetAsPopup(mainHWnd, "ss14cef");
info.RuntimeStyle = CefRuntimeStyle.Alloy;
var impl = new WebViewWindowImpl(this);

View File

@@ -484,27 +484,27 @@ namespace Robust.Client.WebView.Cef
public void FocusEntered()
{
if (_textInputActive)
Owner.Root?.Window?.TextInputStart();
_clyde.TextInputStart();
}
public void FocusExited()
{
if (_textInputActive)
Owner.Root?.Window?.TextInputStop();
_clyde.TextInputStop();
}
public void TextInputStart()
{
_textInputActive = true;
if (Owner.HasKeyboardFocus())
Owner.Root?.Window?.TextInputStart();
_clyde.TextInputStart();
}
public void TextInputStop()
{
_textInputActive = false;
if (Owner.HasKeyboardFocus())
Owner.Root?.Window?.TextInputStop();
_clyde.TextInputStop();
}
private sealed class LiveData
@@ -587,11 +587,8 @@ namespace Robust.Client.WebView.Cef
}
}
protected override void OnAcceleratedPaint(
CefBrowser browser,
CefPaintElementType type,
CefRectangle[] dirtyRects,
in CefAcceleratedPaintInfo info)
protected override void OnAcceleratedPaint(CefBrowser browser, CefPaintElementType type,
CefRectangle[] dirtyRects, IntPtr sharedHandle)
{
// Unused, but we're forced to implement it so.. NOOP.
}

View File

@@ -5,6 +5,7 @@ using System.Net;
using System.Reflection;
using System.Text;
using Robust.Client.Console;
using Robust.Client.Utility;
using Robust.Shared.Configuration;
using Robust.Shared.ContentPack;
using Robust.Shared.IoC;
@@ -24,6 +25,7 @@ namespace Robust.Client.WebView.Cef
[Dependency] private readonly IDependencyCollection _dependencyCollection = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IGameControllerInternal _gameController = default!;
[Dependency] private readonly IResourceManagerInternal _resourceManager = default!;
[Dependency] private readonly IClientConsoleHost _consoleHost = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
@@ -61,7 +63,10 @@ namespace Robust.Client.WebView.Cef
var cachePath = "";
if (_resourceManager.UserData is WritableDirProvider userData)
cachePath = userData.GetFullPath(new ResPath("/cef_cache"));
{
var rootDir = UserDataDir.GetRootUserDataDir(_gameController);
cachePath = Path.Combine(rootDir, "cef_cache", "0");
}
var settings = new CefSettings()
{

View File

@@ -5,7 +5,6 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>WinExe</OutputType>
<ValidateExecutableReferencesMatchSelfContained>false</ValidateExecutableReferencesMatchSelfContained>
<CETCompat>false</CETCompat>
</PropertyGroup>
<ItemGroup>

View File

@@ -504,7 +504,7 @@ public sealed partial class AudioSystem : SharedAudioSystem
var (entity, component) = CreateAndStartPlayingStream(audioParams, stream);
component.Global = true;
component.Source.Global = true;
DirtyField(entity, component, nameof(AudioComponent.Global));
Dirty(entity, component);
return (entity, component);
}

View File

@@ -88,10 +88,10 @@ namespace Robust.Client
{
if (GameInfo != null)
{
GameInfo.TickRate = (ushort) tickrate;
GameInfo.TickRate = (byte) tickrate;
}
_timing.SetTickRateAt((ushort) tickrate, info.TickChanged);
_timing.SetTickRateAt((byte) tickrate, info.TickChanged);
_logger.Info($"Tickrate changed to: {tickrate} on tick {_timing.CurTick}");
}
@@ -395,6 +395,6 @@ namespace Robust.Client
/// </summary>
public int ServerMaxPlayers { get; set; }
public uint TickRate { get; internal set; }
public byte TickRate { get; internal set; }
}
}

View File

@@ -23,7 +23,6 @@ namespace Robust.Client
private Thread? _gameThread;
private ISawmill _logger = default!;
[STAThread]
public static void Main(string[] args)
{
Start(args, new GameControllerOptions());

View File

@@ -382,7 +382,7 @@ namespace Robust.Client
_prof.Initialize();
_resManager.Initialize(Options.LoadConfigAndUserData ? userDataDir : null);
_resManager.Initialize(Options.LoadConfigAndUserData ? userDataDir : null, hideUserDataDir: true);
var mountOptions = _commandLineArgs != null
? MountOptions.Merge(_commandLineArgs.MountOptions, Options.MountOptions)

View File

@@ -101,33 +101,11 @@ namespace Robust.Client.GameObjects
/// <inheritdoc />
public override void Dirty<T>(Entity<T> ent, MetaDataComponent? meta = null)
{
// Client only dirties during prediction
// Client only dirties during prediction
if (_gameTiming.InPrediction)
base.Dirty(ent, meta);
}
public override void DirtyField<T>(EntityUid uid, T comp, string fieldName, MetaDataComponent? metadata = null)
{
// TODO Prediction
// does the client actually need to dirty the field?
// I.e., can't it just dirty the whole component to trigger a reset?
// Client only dirties during prediction
if (_gameTiming.InPrediction)
base.DirtyField(uid, comp, fieldName, metadata);
}
public override void DirtyFields<T>(EntityUid uid, T comp, MetaDataComponent? meta, params ReadOnlySpan<string> fields)
{
// TODO Prediction
// does the client actually need to dirty the field?
// I.e., can't it just dirty the whole component to trigger a reset?
// Client only dirties during prediction
if (_gameTiming.InPrediction)
base.DirtyFields(uid, comp, meta, fields);
}
/// <inheritdoc />
public override void Dirty<T1, T2>(Entity<T1, T2> ent, MetaDataComponent? meta = null)
{

View File

@@ -26,8 +26,6 @@ namespace Robust.Client.GameObjects
protected override void OnAppearanceGetState(EntityUid uid, AppearanceComponent component, ref ComponentGetState args)
{
// TODO Game State
// Force the client to serialize & de-serialize implicitly generated component states.
var clone = CloneAppearanceData(component.AppearanceData);
args.State = new AppearanceComponentState(clone);
}

View File

@@ -5,6 +5,7 @@ using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Utility;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -240,7 +241,7 @@ namespace Robust.Client.GameObjects
#if DEBUG
var uid = GetEntity(netEntity);
if (TryComp(uid, out MetaDataComponent? meta))
if (TryComp<MetaDataComponent>(uid, out var meta))
{
DebugTools.Assert((meta.Flags & ( MetaDataFlags.Detached | MetaDataFlags.InContainer) ) == MetaDataFlags.Detached,
$"Adding entity {ToPrettyString(uid)} to list of expected entities for container {container.ID} in {ToPrettyString(container.Owner)}, despite it already being in a container.");

View File

@@ -1,18 +1,10 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using Robust.Client.UserInterface;
using Robust.Shared.GameObjects;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
namespace Robust.Client.GameObjects;
public sealed class UserInterfaceSystem : SharedUserInterfaceSystem
{
private Dictionary<EntityUid, Dictionary<Enum, Vector2>> _savedPositions = new();
private Dictionary<BoundUserInterface, Control> _registeredControls = new();
public override void Initialize()
{
base.Initialize();
@@ -25,59 +17,6 @@ public sealed class UserInterfaceSystem : SharedUserInterfaceSystem
ProtoManager.PrototypesReloaded -= OnProtoReload;
}
protected override void OnUserInterfaceShutdown(Entity<UserInterfaceComponent> ent, ref ComponentShutdown args)
{
base.OnUserInterfaceShutdown(ent, ref args);
_savedPositions.Remove(ent.Owner);
}
/// <inheritdoc />
public override void OpenUi(Entity<UserInterfaceComponent?> entity, Enum key, bool predicted = false)
{
var player = Player.LocalEntity;
if (player == null)
return;
OpenUi(entity, key, player.Value, predicted);
}
protected override void SavePosition(BoundUserInterface bui)
{
if (!_registeredControls.Remove(bui, out var control))
return;
var keyed = _savedPositions[bui.Owner];
keyed[bui.UiKey] = control.Position;
}
/// <summary>
/// Registers a control so it will later have its position stored by <see cref="SavePosition"/> when the BUI is closed.
/// </summary>
public void RegisterControl(BoundUserInterface bui, Control control)
{
DebugTools.Assert(!_registeredControls.ContainsKey(bui));
_registeredControls[bui] = control;
_savedPositions.GetOrNew(bui.Owner);
}
public override bool TryGetPosition(Entity<UserInterfaceComponent?> entity, Enum key, out Vector2 position)
{
position = default;
if (!_savedPositions.TryGetValue(entity.Owner, out var keyed))
{
return false;
}
if (!keyed.TryGetValue(key, out position))
{
return false;
}
return true;
}
private void OnProtoReload(PrototypesReloadedEventArgs obj)
{
var player = Player.LocalEntity;

View File

@@ -23,6 +23,7 @@ using Robust.Shared.Input;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Network.Messages;
using Robust.Shared.Profiling;
@@ -41,13 +42,13 @@ namespace Robust.Client.GameStates
private uint _nextInputCmdSeq = 1;
private readonly Queue<FullInputCmdMessage> _pendingInputs = new();
private readonly Queue<(uint sequence, GameTick sourceTick, object msg, object sessionMsg)>
private readonly Queue<(uint sequence, GameTick sourceTick, EntityEventArgs msg, object sessionMsg)>
_pendingSystemMessages
= new();
// Game state dictionaries that get used every tick.
private readonly Dictionary<EntityUid, StateData> _toApply = new();
private StateData[] _toApplySorted = default!;
private readonly Dictionary<EntityUid, (NetEntity NetEntity, MetaDataComponent Meta, bool EnteringPvs, GameTick LastApplied, EntityState? curState, EntityState? nextState)> _toApply = new();
private readonly Dictionary<NetEntity, EntityState> _toCreate = new();
private readonly Dictionary<ushort, (IComponent Component, IComponentState? curState, IComponentState? nextState)> _compStateWork = new();
private readonly Dictionary<EntityUid, HashSet<Type>> _pendingReapplyNetStates = new();
private readonly HashSet<NetEntity> _stateEnts = new();
@@ -55,29 +56,15 @@ namespace Robust.Client.GameStates
private readonly List<IComponent> _toRemove = new();
private readonly Dictionary<NetEntity, Dictionary<ushort, IComponentState?>> _outputData = new();
private readonly List<(EntityUid, TransformComponent)> _queuedBroadphaseUpdates = new();
private readonly HashSet<EntityUid> _sorted = new();
private readonly List<NetEntity> _created = new();
private readonly List<NetEntity> _detached = new();
private readonly record struct StateData(
EntityUid Uid,
NetEntity NetEntity,
MetaDataComponent Meta,
bool Created,
bool EnteringPvs,
GameTick LastApplied,
EntityState? CurState,
EntityState? NextState,
HashSet<Type>? PendingReapply);
private readonly ObjectPool<Dictionary<ushort, IComponentState?>> _compDataPool =
new DefaultObjectPool<Dictionary<ushort, IComponentState?>>(new DictPolicy<ushort, IComponentState?>(), 256);
private uint _metaCompNetId;
private uint _xformCompNetId;
[Dependency] private readonly IReplayRecordingManager _replayRecording = default!;
[Dependency] private readonly IComponentFactory _compFactory = default!;
[Dependency] private readonly IClientEntityManagerInternal _entities = default!;
[Dependency] private readonly IPlayerManager _players = default!;
[Dependency] private readonly IClientNetManager _network = default!;
[Dependency] private readonly IBaseClient _client = default!;
@@ -85,7 +72,7 @@ namespace Robust.Client.GameStates
[Dependency] private readonly INetConfigurationManager _config = default!;
[Dependency] private readonly IEntitySystemManager _entitySystemManager = default!;
[Dependency] private readonly IConsoleHost _conHost = default!;
[Dependency] private readonly ClientEntityManager _entities = default!;
[Dependency] private readonly ClientEntityManager _entityManager = default!;
[Dependency] private readonly IInputManager _inputManager = default!;
[Dependency] private readonly ProfManager _prof = default!;
[Dependency] private readonly IRuntimeLog _runtimeLog = default!;
@@ -139,6 +126,7 @@ namespace Robust.Client.GameStates
private bool _resettingPredictedEntities;
private readonly List<EntityUid> _brokenEnts = new();
private readonly List<(EntityUid, NetEntity)> _toStart = new();
/// <inheritdoc />
public void Initialize()
@@ -184,12 +172,6 @@ namespace Robust.Client.GameStates
throw new InvalidOperationException("MetaDataComponent does not have a NetId.");
_metaCompNetId = metaId.Value;
var xformId = _compFactory.GetRegistration(typeof(TransformComponent)).NetID;
if (!xformId.HasValue)
throw new InvalidOperationException("TransformComponent does not have a NetId.");
_xformCompNetId = xformId.Value;
}
private void OnComponentAdded(AddedComponentEventArgs args)
@@ -201,11 +183,11 @@ namespace Robust.Client.GameStates
if (comp.NetID == null)
return;
if (_entities.IsClientSide(args.BaseArgs.Owner))
if (_entityManager.IsClientSide(args.BaseArgs.Owner))
return;
_sawmill.Error($"""
Added component {comp.Name} to entity {_entities.ToPrettyString(args.BaseArgs.Owner)} while resetting predicted entities.
Added component {comp.Name} to entity {_entityManager.ToPrettyString(args.BaseArgs.Owner)} while resetting predicted entities.
Stack trace:
{Environment.StackTrace}
""");
@@ -403,7 +385,7 @@ namespace Robust.Client.GameStates
try
{
#endif
ApplyGameState(curState, nextState);
createdEntities = ApplyGameState(curState, nextState);
#if EXCEPTION_TOLERANCE
}
catch (MissingMetadataException e)
@@ -417,7 +399,7 @@ namespace Robust.Client.GameStates
using (_prof.Group("MergeImplicitData"))
{
MergeImplicitData();
MergeImplicitData(createdEntities);
}
if (_lastProcessedInput < curState.LastProcessedInput)
@@ -474,7 +456,7 @@ namespace Robust.Client.GameStates
using (_prof.Group("Tick"))
{
_entities.TickUpdate((float) _timing.TickPeriod.TotalSeconds, noPredictions: !IsPredictionEnabled, histogram: null);
_entities.TickUpdate((float) _timing.TickPeriod.TotalSeconds, noPredictions: !IsPredictionEnabled);
}
}
@@ -522,7 +504,9 @@ namespace Robust.Client.GameStates
while (hasPendingMessage && pendingMessagesEnumerator.Current.sourceTick <= _timing.CurTick)
{
_entities.EventBus.RaiseEvent(EventSource.Local, pendingMessagesEnumerator.Current.msg);
var msg = pendingMessagesEnumerator.Current.msg;
_entities.EventBus.RaiseEvent(EventSource.Local, msg);
_entities.EventBus.RaiseEvent(EventSource.Local, pendingMessagesEnumerator.Current.sessionMsg);
hasPendingMessage = pendingMessagesEnumerator.MoveNext();
}
@@ -561,7 +545,7 @@ namespace Robust.Client.GameStates
PredictionNeedsResetting = false;
var countReset = 0;
var system = _entitySystemManager.GetEntitySystem<ClientDirtySystem>();
var metaQuery = _entities.GetEntityQuery<MetaDataComponent>();
var metaQuery = _entityManager.GetEntityQuery<MetaDataComponent>();
RemQueue<IComponent> toRemove = new();
foreach (var entity in system.DirtyEntities)
@@ -648,7 +632,7 @@ namespace Robust.Client.GameStates
if (!last.TryGetValue(netId, out var state))
continue;
var comp = _entities.AddComponent(entity, netId, meta);
var comp = _entityManager.AddComponent(entity, netId, meta);
if (_sawmill.Level <= LogLevel.Debug)
_sawmill.Debug($" A component was removed: {comp.GetType()}");
@@ -668,7 +652,7 @@ namespace Robust.Client.GameStates
meta.EntityLastModifiedTick = _timing.LastRealTick;
}
_entities.System<PhysicsSystem>().ResetContacts();
_entityManager.System<PhysicsSystem>().ResetContacts();
// TODO maybe reset more of physics?
// E.g., warm impulses for warm starting?
@@ -687,21 +671,21 @@ namespace Robust.Client.GameStates
/// initial server state for any newly created entity. It does this by simply using the standard <see
/// cref="IEntityManager.GetComponentState"/>.
/// </remarks>
public void MergeImplicitData()
private void MergeImplicitData(IEnumerable<NetEntity> createdEntities)
{
var bus = _entities.EventBus;
var bus = _entityManager.EventBus;
foreach (var netEntity in _created)
foreach (var netEntity in createdEntities)
{
if (!_entities.TryGetEntityData(netEntity, out _, out var meta))
#if EXCEPTION_TOLERANCE
if (!_entityManager.TryGetEntityData(netEntity, out _, out var meta))
{
_sawmill.Error($"Encountered deleted entity while merging implicit data! NetEntity: {netEntity}");
#if !EXCEPTION_TOLERANCE
throw new KeyNotFoundException();
#endif
continue;
}
#else
var (_, meta) = _entityManager.GetEntityData(netEntity);
#endif
var compData = _compDataPool.Get();
_outputData.Add(netEntity, compData);
@@ -710,13 +694,12 @@ namespace Robust.Client.GameStates
{
DebugTools.Assert(component.NetSyncEnabled);
var state = _entities.GetComponentState(bus, component, null, GameTick.Zero);
var state = _entityManager.GetComponentState(bus, component, null, GameTick.Zero);
DebugTools.Assert(state is not IComponentDeltaState);
compData.Add(netId, state);
}
}
_created.Clear();
_processor.MergeImplicitData(_outputData);
foreach (var data in _outputData.Values)
@@ -752,9 +735,10 @@ namespace Robust.Client.GameStates
_config.TickProcessMessages();
}
(IEnumerable<NetEntity> Created, List<NetEntity> Detached) output;
using (_prof.Group("Entity"))
{
ApplyEntityStates(curState, nextState);
output = ApplyEntityStates(curState, nextState);
}
using (_prof.Group("Player"))
@@ -764,13 +748,13 @@ namespace Robust.Client.GameStates
using (_prof.Group("Callback"))
{
GameStateApplied?.Invoke(new GameStateAppliedArgs(curState, _detached));
GameStateApplied?.Invoke(new GameStateAppliedArgs(curState, output.Detached));
}
return _created;
return output.Created;
}
private void ApplyEntityStates(GameState curState, GameState? nextState)
private (IEnumerable<NetEntity> Created, List<NetEntity> Detached) ApplyEntityStates(GameState curState, GameState? nextState)
{
var metas = _entities.GetEntityQuery<MetaDataComponent>();
var xforms = _entities.GetEntityQuery<TransformComponent>();
@@ -778,74 +762,90 @@ namespace Robust.Client.GameStates
var enteringPvs = 0;
_toApply.Clear();
_created.Clear();
_toCreate.Clear();
_pendingReapplyNetStates.Clear();
var curSpan = curState.EntityStates.Span;
// Create new entities
// This is done BEFORE state application to ensure any new parents exist before existing children have their states applied, otherwise, we may have issues with entity transforms!
using (_prof.Group("Create uninitialized entities"))
{
var created = 0;
using var _ = _prof.Group("Create uninitialized entities");
var count = 0;
foreach (var es in curSpan)
{
if (_entities.TryGetEntity(es.NetEntity, out var nUid))
if (_entityManager.TryGetEntity(es.NetEntity, out var nUid))
{
DebugTools.Assert(_entities.EntityExists(nUid));
DebugTools.Assert(_entityManager.EntityExists(nUid));
continue;
}
created++;
CreateNewEntity(es, curState.ToSequence);
count++;
var metaState = (MetaDataComponentState?)es.ComponentChanges.Value?.FirstOrDefault(c => c.NetID == _metaCompNetId).State;
if (metaState == null)
throw new MissingMetadataException(es.NetEntity);
var uid = _entities.CreateEntity(metaState.PrototypeId, out var newMeta);
_toCreate.Add(es.NetEntity, es);
_toApply.Add(uid, (es.NetEntity, newMeta, false, GameTick.Zero, es, null));
// Client creates a client-side net entity for the newly created entity.
// We need to clear this mapping before assigning the real net id.
// TODO NetEntity Jank: prevent the client from creating this in the first place.
_entityManager.ClearNetEntity(newMeta.NetEntity);
_entityManager.SetNetEntity(uid, es.NetEntity, newMeta);
newMeta.LastStateApplied = curState.ToSequence;
// Check if there's any component states awaiting this entity.
if (_entityManager.PendingNetEntityStates.Remove(es.NetEntity, out var value))
{
foreach (var (type, owner) in value)
{
var pending = _pendingReapplyNetStates.GetOrNew(owner);
pending.Add(type);
}
}
}
_prof.WriteValue("Count", ProfData.Int32(created));
_prof.WriteValue("Count", ProfData.Int32(count));
}
// Add entity entities that aren't new to _toCreate.
// In the process, we also check if these entities are re-entering PVS range.
foreach (var es in curSpan)
{
if (!_entities.TryGetEntityData(es.NetEntity, out var uid, out var meta))
if (_toCreate.ContainsKey(es.NetEntity))
continue;
var isEnteringPvs = (meta.Flags & MetaDataFlags.Detached) != 0;
if (!_entityManager.TryGetEntityData(es.NetEntity, out var uid, out var meta))
continue;
bool isEnteringPvs = (meta.Flags & MetaDataFlags.Detached) != 0;
if (isEnteringPvs)
{
// _toApply already contains newly created entities, but these should never be "entering PVS"
DebugTools.Assert(!_toApply.ContainsKey(uid.Value));
meta.Flags &= ~MetaDataFlags.Detached;
enteringPvs++;
}
else if (meta.LastStateApplied >= es.EntityLastModified && meta.LastStateApplied != GameTick.Zero)
{
// _toApply already contains newly created entities, but for those this set should have no effect
DebugTools.Assert(!_toApply.ContainsKey(uid.Value) || meta.LastStateApplied == curState.ToSequence);
meta.LastStateApplied = curState.ToSequence;
continue;
}
// Any newly created entities already added to _toApply should've already been caught by the previous continue
DebugTools.Assert(!_toApply.ContainsKey(uid.Value));
_toApply.Add(uid.Value, new(uid.Value, es.NetEntity, meta, false, isEnteringPvs, meta.LastStateApplied, es, null, null));
_toApply.Add(uid.Value, (es.NetEntity, meta, isEnteringPvs, meta.LastStateApplied, es, null));
meta.LastStateApplied = curState.ToSequence;
}
// Detach entities to null space
var containerSys = _entitySystemManager.GetEntitySystem<ContainerSystem>();
var lookupSys = _entitySystemManager.GetEntitySystem<EntityLookupSystem>();
ProcessPvsDeparture(curState.ToSequence, metas, xforms, xformSys, containerSys, lookupSys);
var detached = ProcessPvsDeparture(curState.ToSequence, metas, xforms, xformSys, containerSys, lookupSys);
// Check next state (AFTER having created new entities introduced in curstate)
if (nextState != null)
{
foreach (var es in nextState.EntityStates.Span)
{
if (!_entities.TryGetEntityData(es.NetEntity, out var uid, out var meta))
if (!_entityManager.TryGetEntityData(es.NetEntity, out var uid, out var meta))
continue;
// Does the next state actually have any future information about this entity that could be used for interpolation?
@@ -854,14 +854,15 @@ namespace Robust.Client.GameStates
ref var state = ref CollectionsMarshal.GetValueRefOrAddDefault(_toApply, uid.Value, out var exists);
state = exists
? state with {NextState = es}
: new(uid.Value, es.NetEntity, meta, false, false, GameTick.Zero, null, es, null);
if (exists)
state = (es.NetEntity, meta, state.EnteringPvs, state.LastApplied, state.curState, es);
else
state = (es.NetEntity, meta, false, GameTick.Zero, null, es);
}
}
// Check pending states and see if we need to force any entities to re-run component states.
foreach (var (uid, pending) in _pendingReapplyNetStates)
foreach (var uid in _pendingReapplyNetStates.Keys)
{
// Original entity referencing the NetEntity may have been deleted.
if (!metas.TryGetComponent(uid, out var meta))
@@ -878,30 +879,51 @@ namespace Robust.Client.GameStates
DebugTools.Assert(!curState.EntityDeletions.Value.Contains(meta.NetEntity));
// State already being re-applied so don't bulldoze it.
ref var state = ref CollectionsMarshal.GetValueRefOrAddDefault(_toApply, uid, out var exists);
state = exists
? state with {PendingReapply = pending}
: new(uid, meta.NetEntity, meta, false, false, GameTick.Zero, null, null, pending);
if (exists)
continue;
state = (meta.NetEntity, meta, false, GameTick.Zero, null, null);
}
_queuedBroadphaseUpdates.Clear();
using (_prof.Group("Sort States"))
{
SortStates(_toApply);
}
// Apply entity states.
using (_prof.Group("Apply States"))
{
var span = _toApplySorted.AsSpan(0, _toApply.Count);
foreach (ref var data in span)
foreach (var (entity, data) in _toApply)
{
ApplyEntState(data, curState.ToSequence);
#if EXCEPTION_TOLERANCE
try
{
#endif
HandleEntityState(entity, data.NetEntity, data.Meta, _entities.EventBus, data.curState,
data.nextState, data.LastApplied, curState.ToSequence, data.EnteringPvs);
#if EXCEPTION_TOLERANCE
}
catch (Exception e)
{
_sawmill.Error($"Caught exception while applying entity state. Entity: {_entities.ToPrettyString(entity)}. Exception: {e}");
_entityManager.DeleteEntity(entity);
RequestFullState();
continue;
}
#endif
if (!data.EnteringPvs)
continue;
// Now that things like collision data, fixtures, and positions have been updated, we queue a
// broadphase update. However, if this entity is parented to some other entity also re-entering PVS,
// we only need to update it's parent (as it recursively updates children anyways).
var xform = xforms.GetComponent(entity);
DebugTools.Assert(xform.Broadphase == BroadphaseData.Invalid);
xform.Broadphase = null;
if (!_toApply.TryGetValue(xform.ParentUid, out var parent) || !parent.EnteringPvs)
_queuedBroadphaseUpdates.Add((entity, xform));
}
Array.Clear(_toApplySorted, 0, _toApply.Count);
_prof.WriteValue("Count", ProfData.Int32(_toApply.Count));
}
@@ -936,166 +958,14 @@ namespace Robust.Client.GameStates
}
}
// Delete any entities that failed to properly initialize/start
foreach (var entity in _brokenEnts)
{
_entities.DeleteEntity(entity);
}
_brokenEnts.Clear();
// Initialize and start the newly created entities.
if (_toCreate.Count > 0)
InitializeAndStart(_toCreate, metas, xforms);
_prof.WriteValue("State Size", ProfData.Int32(curSpan.Length));
_prof.WriteValue("Entered PVS", ProfData.Int32(enteringPvs));
}
private void ApplyEntState(in StateData data, GameTick toTick)
{
try
{
HandleEntityState(data, _entities.EventBus, toTick);
}
catch (Exception e)
{
_sawmill.Error($"Caught exception while applying entity state. Entity: {_entities.ToPrettyString(data.Uid)}. Exception: {e}");
_brokenEnts.Add(data.Uid);
RequestFullState();
#if !EXCEPTION_TOLERANCE
throw;
#endif
return;
}
if (data.Created)
{
try
{
_entities.InitializeEntity(data.Uid, data.Meta);
_entities.StartEntity(data.Uid);
}
catch (Exception e)
{
_sawmill.Error(
$"Caught exception while initializing or starting entity: {_entities.ToPrettyString(data.Uid)}. Exception: {e}");
_brokenEnts.Add(data.Uid);
RequestFullState();
#if !EXCEPTION_TOLERANCE
throw;
#endif
return;
}
}
if (!data.EnteringPvs)
return;
// Now that things like collision data, fixtures, and positions have been updated, we queue a
// broadphase update. However, if this entity is parented to some other entity also re-entering PVS,
// we only need to update it's parent (as it recursively updates children anyways).
var xform = _entities.TransformQuery.Comp(data.Uid);
DebugTools.Assert(xform.Broadphase == BroadphaseData.Invalid);
xform.Broadphase = null;
if (!_toApply.TryGetValue(xform.ParentUid, out var parent) || !parent.EnteringPvs)
_queuedBroadphaseUpdates.Add((data.Uid, xform));
}
private void CreateNewEntity(EntityState state, GameTick toTick)
{
// TODO GAME STATE
// store MetaData & Transform information separately.
var metaState =
(MetaDataComponentState?) state.ComponentChanges.Value?.FirstOrDefault(c => c.NetID == _metaCompNetId)
.State;
if (metaState == null)
throw new MissingMetadataException(state.NetEntity);
var uid = _entities.CreateEntity(metaState.PrototypeId, out var newMeta);
_toApply.Add(uid, new(uid, state.NetEntity, newMeta, true, false, GameTick.Zero, state, null, null));
_created.Add(state.NetEntity);
// Client creates a client-side net entity for the newly created entity.
// We need to clear this mapping before assigning the real net id.
// TODO NetEntity Jank: prevent the client from creating this in the first place.
_entities.ClearNetEntity(newMeta.NetEntity);
_entities.SetNetEntity(uid, state.NetEntity, newMeta);
newMeta.LastStateApplied = toTick;
// Check if there's any component states awaiting this entity.
if (!_entities.PendingNetEntityStates.Remove(state.NetEntity, out var value))
return;
foreach (var (type, owner) in value)
{
var pending = _pendingReapplyNetStates.GetOrNew(owner);
pending.Add(type);
}
}
/// <summary>
/// Sort states to ensure that we always apply states, initialize, and start parent entities before any of their
/// children.
/// </summary>
private void SortStates(Dictionary<EntityUid, StateData> toApply)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (_toApplySorted == null || _toApplySorted.Length < toApply.Count)
Array.Resize(ref _toApplySorted, toApply.Count);
_sorted.Clear();
var i = 0;
foreach (var (ent, data) in toApply)
{
AddToSorted(ent, data, ref i);
}
DebugTools.AssertEqual(i, toApply.Count);
}
private void AddToSorted(EntityUid ent, in StateData data, ref int i)
{
if (!_sorted.Add(ent))
return;
EnsureParentsSorted(ent, data, ref i);
_toApplySorted[i++] = data;
}
private void EnsureParentsSorted(EntityUid ent, in StateData data, ref int i)
{
var parent = GetStateParent(ent, data);
while (parent != EntityUid.Invalid)
{
if (_toApply.TryGetValue(parent, out var parentData))
{
AddToSorted(parent, parentData, ref i);
// The above method will handle the rest of the transform hierarchy, so we can just return early.
return;
}
parent = _entities.TransformQuery.GetComponent(parent).ParentUid;
}
}
/// <summary>
/// Get the entity's parent in the game state that is being applies. I.e., if the state contains a new
/// transform state, get the parent from that. Otherwise, return the entity's current parent.
/// </summary>
private EntityUid GetStateParent(EntityUid uid, in StateData data)
{
// TODO GAME STATE
// store MetaData & Transform information separately.
if (data.CurState != null
&& data.CurState.ComponentChanges.Value
.TryFirstOrNull(c => c.NetID == _xformCompNetId, out var found))
{
var state = (TransformComponentState) found.Value.State!;
return _entities.GetEntity(state.ParentID);
}
return _entities.TransformQuery.GetComponent(uid).ParentUid;
return (_toCreate.Keys, detached);
}
/// <inheritdoc />
@@ -1130,7 +1000,7 @@ namespace Robust.Client.GameStates
_toDelete.Clear();
// Client side entities won't need the transform, but that should always be a tiny minority of entities
var metaQuery = _entities.AllEntityQueryEnumerator<MetaDataComponent, TransformComponent>();
var metaQuery = _entityManager.AllEntityQueryEnumerator<MetaDataComponent, TransformComponent>();
while (metaQuery.MoveNext(out var ent, out var metadata, out var xform))
{
@@ -1197,9 +1067,9 @@ namespace Robust.Client.GameStates
foreach (var netEntity in delSpan)
{
// Don't worry about this for later.
_entities.PendingNetEntityStates.Remove(netEntity);
_entityManager.PendingNetEntityStates.Remove(netEntity);
if (!_entities.TryGetEntity(netEntity, out var id))
if (!_entityManager.TryGetEntity(netEntity, out var id))
continue;
if (!xforms.TryGetComponent(id, out var xform))
@@ -1229,10 +1099,9 @@ namespace Robust.Client.GameStates
var containerSys = _entitySystemManager.GetEntitySystem<ContainerSystem>();
var lookupSys = _entitySystemManager.GetEntitySystem<EntityLookupSystem>();
Detach(GameTick.MaxValue, null, entities, metas, xforms, xformSys, containerSys, lookupSys);
_detached.Clear();
}
private void ProcessPvsDeparture(
private List<NetEntity> ProcessPvsDeparture(
GameTick toTick,
EntityQuery<MetaDataComponent> metas,
EntityQuery<TransformComponent> xforms,
@@ -1241,23 +1110,25 @@ namespace Robust.Client.GameStates
EntityLookupSystem lookupSys)
{
var toDetach = _processor.GetEntitiesToDetach(toTick, _pvsDetachBudget);
var detached = new List<NetEntity>();
if (toDetach.Count == 0)
return;
return detached;
// TODO optimize
// If an entity is leaving PVS, so are all of its children. If we can preserve the hierarchy we can avoid
// things like container insertion and ejection.
using var _ = _prof.Group("Leave PVS");
detached.EnsureCapacity(toDetach.Count);
_detached.Clear();
foreach (var (tick, ents) in toDetach)
{
Detach(tick, toTick, ents, metas, xforms, xformSys, containerSys, lookupSys);
Detach(tick, toTick, ents, metas, xforms, xformSys, containerSys, lookupSys, detached);
}
_prof.WriteValue("Count", ProfData.Int32(_detached.Count));
_prof.WriteValue("Count", ProfData.Int32(detached.Count));
return detached;
}
private void Detach(GameTick maxTick,
@@ -1267,11 +1138,12 @@ namespace Robust.Client.GameStates
EntityQuery<TransformComponent> xforms,
SharedTransformSystem xformSys,
ContainerSystem containerSys,
EntityLookupSystem lookupSys)
EntityLookupSystem lookupSys,
List<NetEntity>? detached = null)
{
foreach (var netEntity in entities)
{
if (!_entities.TryGetEntityData(netEntity, out var ent, out var meta))
if (!_entityManager.TryGetEntityData(netEntity, out var ent, out var meta))
continue;
if (meta.LastStateApplied > maxTick)
@@ -1312,75 +1184,159 @@ namespace Robust.Client.GameStates
containerSys.AddExpectedEntity(netEntity, container);
}
_detached.Add(netEntity);
detached?.Add(netEntity);
}
}
private void HandleEntityState(in StateData data, IEventBus bus, GameTick toTick)
private void InitializeAndStart(
Dictionary<NetEntity, EntityState> toCreate,
EntityQuery<MetaDataComponent> metas,
EntityQuery<TransformComponent> xforms)
{
_toStart.Clear();
using (_prof.Group("Initialize Entity"))
{
EntityUid entity = default;
foreach (var netEntity in toCreate.Keys)
{
(entity, var meta) = _entityManager.GetEntityData(netEntity);
InitializeRecursive(entity, meta, metas, xforms);
}
}
using (_prof.Group("Start Entity"))
{
foreach (var (entity, netEntity) in _toStart)
{
try
{
_entities.StartEntity(entity);
}
catch (Exception e)
{
_sawmill.Error($"Server entity threw in Start: nent={netEntity}, ent={_entityManager.ToPrettyString(entity)}");
_runtimeLog.LogException(e, $"{nameof(ClientGameStateManager)}.{nameof(InitializeAndStart)}");
_toCreate.Remove(netEntity);
_brokenEnts.Add(entity);
#if !EXCEPTION_TOLERANCE
throw;
#endif
}
}
}
foreach (var entity in _brokenEnts)
{
_entityManager.DeleteEntity(entity);
}
_brokenEnts.Clear();
}
private void InitializeRecursive(
EntityUid entity,
MetaDataComponent meta,
EntityQuery<MetaDataComponent> metas,
EntityQuery<TransformComponent> xforms)
{
var xform = xforms.GetComponent(entity);
if (xform.ParentUid is {Valid: true} parent)
{
var parentMeta = metas.GetComponent(parent);
if (parentMeta.EntityLifeStage < EntityLifeStage.Initialized)
InitializeRecursive(parent, parentMeta, metas, xforms);
}
if (meta.EntityLifeStage >= EntityLifeStage.Initialized)
{
// Was probably already initialized because one of its children appeared earlier in the list.
DebugTools.AssertEqual(_toStart.Count(x => x.Item1 == entity), 1);
return;
}
try
{
_entities.InitializeEntity(entity, meta);
_toStart.Add((entity, meta.NetEntity));
}
catch (Exception e)
{
_sawmill.Error($"Server entity threw in Init: nent={meta.NetEntity}, ent={_entities.ToPrettyString(entity)}");
_runtimeLog.LogException(e, $"{nameof(ClientGameStateManager)}.{nameof(InitializeAndStart)}");
_toCreate.Remove(meta.NetEntity);
_brokenEnts.Add(entity);
#if !EXCEPTION_TOLERANCE
throw;
#endif
}
}
private void HandleEntityState(EntityUid uid, NetEntity netEntity, MetaDataComponent meta, IEventBus bus, EntityState? curState,
EntityState? nextState, GameTick lastApplied, GameTick toTick, bool enteringPvs)
{
_compStateWork.Clear();
// First remove any deleted components
if (data.CurState?.NetComponents is {} netComps)
if (curState?.NetComponents != null)
{
_toRemove.Clear();
foreach (var (id, comp) in data.Meta.NetComponents)
foreach (var (id, comp) in meta.NetComponents)
{
DebugTools.Assert(comp.NetSyncEnabled);
if (!netComps.Contains(id))
if (!curState.NetComponents.Contains(id))
_toRemove.Add(comp);
}
foreach (var comp in _toRemove)
{
_entities.RemoveComponent(data.Uid, comp, data.Meta);
_entities.RemoveComponent(uid, comp, meta);
}
}
if (data.EnteringPvs)
if (enteringPvs)
{
// last-server state has already been updated with new information from curState
// --> simply reset to the most recent server state.
//
// as to why we need to reset: because in the process of detaching to null-space, we will have dirtied
// the entity. most notably, all entities will have been ejected from their containers.
foreach (var (id, state) in _processor.GetLastServerStates(data.NetEntity))
foreach (var (id, state) in _processor.GetLastServerStates(netEntity))
{
if (!data.Meta.NetComponents.TryGetValue(id, out var comp))
if (!meta.NetComponents.TryGetValue(id, out var comp))
{
comp = _compFactory.GetComponent(id);
_entities.AddComponent(data.Uid, comp, true, metadata: data.Meta);
_entityManager.AddComponent(uid, comp, true, metadata: meta);
}
_compStateWork[id] = (comp, state, null);
}
}
else if (data.CurState != null)
else if (curState != null)
{
foreach (var compChange in data.CurState.ComponentChanges.Span)
foreach (var compChange in curState.ComponentChanges.Span)
{
if (!data.Meta.NetComponents.TryGetValue(compChange.NetID, out var comp))
if (!meta.NetComponents.TryGetValue(compChange.NetID, out var comp))
{
comp = _compFactory.GetComponent(compChange.NetID);
_entities.AddComponent(data.Uid, comp, true, metadata: data.Meta);
_entityManager.AddComponent(uid, comp, true, metadata:meta);
}
else if (compChange.LastModifiedTick <= data.LastApplied && data.LastApplied != GameTick.Zero)
else if (compChange.LastModifiedTick <= lastApplied && lastApplied != GameTick.Zero)
continue;
_compStateWork[compChange.NetID] = (comp, compChange.State, null);
}
}
if (data.NextState != null)
if (nextState != null)
{
foreach (var compState in data.NextState.ComponentChanges.Span)
foreach (var compState in nextState.ComponentChanges.Span)
{
if (compState.LastModifiedTick != toTick + 1)
continue;
if (!data.Meta.NetComponents.TryGetValue(compState.NetID, out var comp))
if (!meta.NetComponents.TryGetValue(compState.NetID, out var comp))
{
// The component can be null here due to interp, because the NEXT state will have a new
// component, but the component does not yet exist.
@@ -1398,10 +1354,9 @@ namespace Robust.Client.GameStates
}
// If we have a NetEntity we reference come in then apply their state.
DebugTools.Assert(_pendingReapplyNetStates.ContainsKey(data.Uid) == (data.PendingReapply != null));
if (data.PendingReapply is {} reapplyTypes)
if (_pendingReapplyNetStates.TryGetValue(uid, out var reapplyTypes))
{
var lastState = _processor.GetLastServerStates(data.NetEntity);
var lastState = _processor.GetLastServerStates(netEntity);
foreach (var type in reapplyTypes)
{
@@ -1411,7 +1366,7 @@ namespace Robust.Client.GameStates
if (netId == null)
continue;
if (!data.Meta.NetComponents.TryGetValue(netId.Value, out var comp) ||
if (!meta.NetComponents.TryGetValue(netId.Value, out var comp) ||
!lastState.TryGetValue(netId.Value, out var lastCompState))
{
continue;
@@ -1433,7 +1388,7 @@ namespace Robust.Client.GameStates
continue;
var handleState = new ComponentHandleState(cur, next);
bus.RaiseComponentEvent(data.Uid, comp, ref handleState);
bus.RaiseComponentEvent(uid, comp, ref handleState);
}
}
@@ -1555,7 +1510,7 @@ namespace Robust.Client.GameStates
{
using var _ = _timing.StartStateApplicationArea();
var query = _entities.AllEntityQueryEnumerator<MetaDataComponent>();
var query = _entityManager.AllEntityQueryEnumerator<MetaDataComponent>();
while (query.MoveNext(out var uid, out var meta))
{
@@ -1581,14 +1536,14 @@ namespace Robust.Client.GameStates
if (!meta.NetComponents.TryGetValue(id, out var comp))
{
comp = _compFactory.GetComponent(id);
_entities.AddComponent(uid, comp, true, meta);
_entityManager.AddComponent(uid, comp, true, meta);
}
if (state == null)
continue;
var handleState = new ComponentHandleState(state, null);
_entities.EventBus.RaiseComponentEvent(uid, comp, ref handleState);
_entityManager.EventBus.RaiseComponentEvent(uid, comp, ref handleState);
}
// ensure we don't have any extra components

View File

@@ -82,8 +82,6 @@ namespace Robust.Client.GameStates
/// </summary>
IEnumerable<NetEntity> ApplyGameState(GameState curState, GameState? nextState);
void MergeImplicitData();
/// <summary>
/// Resets any entities that have changed while predicting future ticks.
/// </summary>

View File

@@ -26,7 +26,6 @@ namespace Robust.Client.GameStates
[Dependency] private readonly IClientNetManager _netManager = default!;
[Dependency] private readonly IClientGameStateManager _gameStateManager = default!;
[Dependency] private readonly IComponentFactory _componentFactory = default!;
[Dependency] private readonly IConsoleHost _host = default!;
[Dependency] private readonly IEntityManager _entManager = default!;
private const int HistorySize = 60 * 5; // number of ticks to keep in history.
@@ -79,7 +78,7 @@ namespace Robust.Client.GameStates
string? entStateString = null;
string? entDelString = null;
var conShell = _host.LocalShell;
var conShell = IoCManager.Resolve<IConsoleHost>().LocalShell;
var entStates = args.AppliedState.EntityStates;
if (entStates.HasContents)

View File

@@ -1,5 +0,0 @@
using Robust.Shared.GameStates;
namespace Robust.Client.GameStates;
public sealed partial class PvsOverrideSystem : SharedPvsOverrideSystem;

View File

@@ -125,7 +125,7 @@ namespace Robust.Client.Graphics.Clyde
{
DebugTools.Assert(space != OverlaySpace.ScreenSpaceBelowWorld && space != OverlaySpace.ScreenSpace);
var args = new OverlayDrawArgs(space, null, vp, _renderHandle, new UIBox2i((0, 0), vp.Size), vp.Eye!.Position.MapId, worldBox, worldBounds);
var args = new OverlayDrawArgs(space, null, vp, _renderHandle.DrawingHandleWorld, new UIBox2i((0, 0), vp.Size), vp.Eye!.Position.MapId, worldBox, worldBounds);
if (!overlay.BeforeDraw(args))
return;
@@ -165,7 +165,7 @@ namespace Robust.Client.Graphics.Clyde
private void RenderOverlaysDirect(
Viewport vp,
IViewportControl vpControl,
IRenderHandle handle,
DrawingHandleBase handle,
OverlaySpace space,
in UIBox2i bounds)
{
@@ -215,6 +215,8 @@ namespace Robust.Client.Graphics.Clyde
}
}
_overlays.Sort(OverlayComparer.Instance);
return _overlays;
}
@@ -572,5 +574,17 @@ namespace Robust.Client.Graphics.Clyde
return new Box2Rotated(aabb, rotation, aabb.Center);
}
private sealed class OverlayComparer : IComparer<Overlay>
{
public static readonly OverlayComparer Instance = new();
public int Compare(Overlay? x, Overlay? y)
{
var zX = x?.ZIndex ?? 0;
var zY = y?.ZIndex ?? 0;
return zX.CompareTo(zY);
}
}
}
}

View File

@@ -362,11 +362,6 @@ namespace Robust.Client.Graphics.Clyde
rect.BottomLeft, rect.BottomRight, color, subRegion);
}
public override void DrawTexture(Texture texture, Vector2 position, Color? modulate = null)
{
base.DrawTexture(texture, position, modulate);
}
/// <summary>
/// Draws an entity.
/// </summary>

View File

@@ -171,7 +171,7 @@ namespace Robust.Client.Graphics.Clyde
}
public void RenderScreenOverlaysBelow(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds)
{
@@ -179,7 +179,7 @@ namespace Robust.Client.Graphics.Clyde
}
public void RenderScreenOverlaysAbove(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds)
{

View File

@@ -109,8 +109,8 @@ namespace Robust.Client.Graphics.Clyde
case "glfw":
winImpl = new GlfwWindowingImpl(this, _deps);
break;
case "sdl3":
winImpl = new Sdl3WindowingImpl(this, _deps);
case "sdl2":
winImpl = new Sdl2WindowingImpl(this, _deps);
break;
default:
_logManager.GetSawmill("clyde.win").Log(
@@ -467,7 +467,26 @@ namespace Robust.Client.Graphics.Clyde
_windowing!.RunOnWindowThread(a);
}
public IFileDialogManager? FileDialogImpl => _windowing as IFileDialogManager;
public void TextInputSetRect(UIBox2i rect)
{
DebugTools.AssertNotNull(_windowing);
_windowing!.TextInputSetRect(rect);
}
public void TextInputStart()
{
DebugTools.AssertNotNull(_windowing);
_windowing!.TextInputStart();
}
public void TextInputStop()
{
DebugTools.AssertNotNull(_windowing);
_windowing!.TextInputStop();
}
private abstract class WindowReg
{
@@ -571,27 +590,6 @@ namespace Robust.Client.Graphics.Clyde
remove => Reg.Resized -= value;
}
public void TextInputSetRect(UIBox2i rect, int cursor)
{
DebugTools.AssertNotNull(_clyde._windowing);
_clyde._windowing!.TextInputSetRect(Reg, rect, cursor);
}
public void TextInputStart()
{
DebugTools.AssertNotNull(_clyde._windowing);
_clyde._windowing!.TextInputStart(Reg);
}
public void TextInputStop()
{
DebugTools.AssertNotNull(_clyde._windowing);
_clyde._windowing!.TextInputStop(Reg);
}
public nint? WindowsHWnd => _clyde._windowing!.WindowGetWin32Window(Reg);
}

View File

@@ -7,7 +7,6 @@ using JetBrains.Annotations;
using Robust.Client.Audio;
using Robust.Client.Input;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Graphics;
using Robust.Shared.Map;
@@ -285,8 +284,6 @@ namespace Robust.Client.Graphics.Clyde
action();
}
public IFileDialogManager? FileDialogImpl => null;
private sealed class DummyCursor : ICursor
{
public void Dispose()
@@ -497,7 +494,7 @@ namespace Robust.Client.Graphics.Clyde
}
public void RenderScreenOverlaysBelow(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds)
{
@@ -505,7 +502,7 @@ namespace Robust.Client.Graphics.Clyde
}
public void RenderScreenOverlaysAbove(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds)
{
@@ -534,21 +531,6 @@ namespace Robust.Client.Graphics.Clyde
public event Action<WindowDestroyedEventArgs>? Destroyed;
public event Action<WindowResizedEventArgs>? Resized { add { } remove { } }
public void TextInputSetRect(UIBox2i rect, int cursor)
{
// Nop.
}
public void TextInputStart()
{
// Nop.
}
public void TextInputStop()
{
// Nop.
}
public void MaximizeOnMonitor(IClydeMonitor monitor)
{
}

View File

@@ -96,8 +96,7 @@ namespace Robust.Client.Graphics.Clyde
private void ProcessEventChar(EventChar ev)
{
var windowReg = FindWindow(ev.Window);
if (windowReg is not { TextInputActive: true })
if (!_textInputActive)
return;
_clyde.SendText(new TextEnteredEventArgs(new Rune(ev.CodePoint).ToString()));

View File

@@ -468,8 +468,6 @@ namespace Robust.Client.Graphics.Clyde
GLFW.WindowHint(WindowHintInt.AlphaBits, 8);
GLFW.WindowHint(WindowHintInt.StencilBits, 8);
GLFW.WindowHint(WindowHintBool.Decorated, (parameters.Styles & OSWindowStyles.NoTitleBar) == 0);
var window = GLFW.CreateWindow(
parameters.Width, parameters.Height,
parameters.Title,
@@ -487,12 +485,23 @@ namespace Robust.Client.Graphics.Clyde
GLFW.MaximizeWindow(window);
}
if ((parameters.Styles & OSWindowStyles.NoTitleBar) != 0)
{
GLFW.WindowHint(WindowHintBool.Decorated, false);
}
if ((parameters.Styles & OSWindowStyles.NoTitleOptions) != 0)
{
if (OperatingSystem.IsWindows())
{
var hWnd = (HWND) GLFW.GetWin32Window(window);
WsiShared.SetWindowStyleNoTitleOptionsWindows(hWnd);
DebugTools.Assert(hWnd != HWND.NULL);
Windows.SetWindowLongPtrW(
hWnd,
GWL.GWL_STYLE,
// Cast to long here to work around a bug in rider with nint bitwise operators.
(nint)((long)Windows.GetWindowLongPtrW(hWnd, GWL.GWL_STYLE) & ~WS.WS_SYSMENU));
}
else if (OperatingSystem.IsLinux())
{
@@ -500,7 +509,23 @@ namespace Robust.Client.Graphics.Clyde
{
var x11Window = (X11Window)GLFW.GetX11Window(window);
var x11Display = (Display*) GLFW.GetX11Display(window);
WsiShared.SetWindowStyleNoTitleOptionsX11(x11Display, x11Window);
DebugTools.Assert(x11Window != X11Window.NULL);
// https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html#idm46181547486832
var newPropValString = Marshal.StringToCoTaskMemUTF8("_NET_WM_WINDOW_TYPE_DIALOG");
var newPropVal = Xlib.XInternAtom(x11Display, (sbyte*)newPropValString, Xlib.False);
DebugTools.Assert(newPropVal != Atom.NULL);
var propNameString = Marshal.StringToCoTaskMemUTF8("_NET_WM_WINDOW_TYPE");
#pragma warning disable CA1806
// [display] [window] [property] [type] [format (8, 16,32)] [mode] [data] [element count]
Xlib.XChangeProperty(x11Display, x11Window,
Xlib.XInternAtom(x11Display, (sbyte*)propNameString, Xlib.False), // should never be null; part of spec
Xlib.XA_ATOM, 32, Xlib.PropModeReplace,
(byte*)&newPropVal, 1);
#pragma warning restore CA1806
Marshal.FreeCoTaskMem(newPropValString);
Marshal.FreeCoTaskMem(propNameString);
}
catch (EntryPointNotFoundException)
{
@@ -618,16 +643,16 @@ namespace Robust.Client.Graphics.Clyde
return reg;
}
private GlfwWindowReg? FindWindow(nint window) => FindWindow((Window*) window);
private WindowReg? FindWindow(nint window) => FindWindow((Window*) window);
private GlfwWindowReg? FindWindow(Window* window)
private WindowReg? FindWindow(Window* window)
{
foreach (var windowReg in _clyde._windows)
{
var glfwReg = (GlfwWindowReg) windowReg;
if (glfwReg.GlfwWindow == window)
{
return glfwReg;
return windowReg;
}
}
@@ -714,23 +739,23 @@ namespace Robust.Client.Graphics.Clyde
return (void*) GLFW.GetProcAddress(procName);
}
public void TextInputSetRect(WindowReg reg, UIBox2i rect, int cursor)
public void TextInputSetRect(UIBox2i rect)
{
// Not supported on GLFW.
}
public void TextInputStart(WindowReg reg)
public void TextInputStart()
{
// Not properly supported on GLFW.
((GlfwWindowReg)reg).TextInputActive = true;
_textInputActive = true;
}
public void TextInputStop(WindowReg reg)
public void TextInputStop()
{
// Not properly supported on GLFW.
((GlfwWindowReg)reg).TextInputActive = false;
_textInputActive = false;
}
private void CheckWindowDisposed(WindowReg reg)
@@ -745,10 +770,6 @@ namespace Robust.Client.Graphics.Clyde
// Kept around to avoid it being GCd.
public CursorImpl? Cursor;
// While GLFW does not provide proper IME APIs, we can at least emulate SDL3's StartTextInput() system.
// This will ensure some level of consistency between the backends.
public bool TextInputActive;
}
}
}

View File

@@ -25,6 +25,10 @@ namespace Robust.Client.Graphics.Clyde
private bool _glfwInitialized;
private bool _win32Experience;
// While GLFW does not provide proper IME APIs, we can at least emulate SDL2's StartTextInput() system.
// This will ensure some level of consistency between the backends.
private bool _textInputActive;
public GlfwWindowingImpl(Clyde clyde, IDependencyCollection deps)
{
_clyde = clyde;

View File

@@ -66,9 +66,9 @@ namespace Robust.Client.Graphics.Clyde
void RunOnWindowThread(Action a);
// IME
void TextInputSetRect(WindowReg reg, UIBox2i rect, int cursor);
void TextInputStart(WindowReg reg);
void TextInputStop(WindowReg reg);
void TextInputSetRect(UIBox2i rect);
void TextInputStart();
void TextInputStop();
string GetDescription();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,25 +0,0 @@
/* SDL3-CS - C# Bindings for SDL3
*
* Copyright (c) 2024 Colin Jackson
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in a
* product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* Colin "cryy22" Jackson <c@cryy22.art>
*
*/

View File

@@ -1,56 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace SDL3;
public static partial class SDL
{
// Extensions to SDL3-CS that aren't part of the main library.
[LibraryImport(nativeLibName)]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe partial void SDL_SetLogOutputFunction(delegate* unmanaged[Cdecl] <void*, int, SDL_LogPriority, byte*, void> callback, void* userdata);
[LibraryImport(nativeLibName)]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe partial SDLBool SDL_AddEventWatch(delegate* unmanaged[Cdecl] <void*, SDL_Event*, byte> filter, void* userdata);
[LibraryImport(nativeLibName)]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe partial void SDL_RemoveEventWatch(delegate* unmanaged[Cdecl] <void*, SDL_Event*, byte> filter, void* userdata);
[LibraryImport(nativeLibName, StringMarshalling = StringMarshalling.Utf8)]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe partial void SDL_ShowFileDialogWithProperties(int type, delegate* unmanaged[Cdecl]<void*, byte**, int, void> callback, void* userdata, uint properties);
[LibraryImport(nativeLibName, EntryPoint = "SDL_WaitEvent")]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
public static partial SDLBool SDL_WaitEventRef(ref SDL_Event @event);
public const byte SDL_BUTTON_LEFT = 1;
public const byte SDL_BUTTON_MIDDLE = 2;
public const byte SDL_BUTTON_RIGHT = 3;
public const byte SDL_BUTTON_X1 = 4;
public const byte SDL_BUTTON_X2 = 5;
public const int SDL_GL_CONTEXT_PROFILE_CORE = 0x0001;
public const int SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002;
public const int SDL_GL_CONTEXT_PROFILE_ES = 0x0004;
public const int SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001;
public const int SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002;
public const int SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004;
public const int SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008;
public const int SDL_FILEDIALOG_OPENFILE = 0;
public const int SDL_FILEDIALOG_SAVEFILE = 1;
public const int SDL_FILEDIALOG_OPENFOLDER = 2;
public const string SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER = "SDL.filedialog.nfilters";
public const string SDL_PROP_FILE_DIALOG_FILTERS_POINTER = "SDL.filedialog.filters";
public static int SDL_VERSIONNUM_MAJOR(int version) => version / 1000000;
public static int SDL_VERSIONNUM_MINOR(int version) => version / 1000 % 1000;
public static int SDL_VERSIONNUM_MICRO(int version) => version % 1000;
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,15 +3,16 @@ using System.Collections.Generic;
using Robust.Client.Utility;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
using SDL3;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using static SDL2.SDL;
using static SDL2.SDL.SDL_SystemCursor;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
private sealed partial class Sdl2WindowingImpl : IWindowingImpl
{
private readonly Dictionary<ClydeHandle, WinThreadCursorReg> _winThreadCursors = new();
private readonly CursorImpl[] _standardCursors = new CursorImpl[(int)StandardCursorShape.CountCursors];
@@ -27,32 +28,31 @@ internal partial class Clyde
image.GetPixelSpan().CopyTo(cloneImg.GetPixelSpan());
var id = _clyde.AllocRid();
SendCmd(new CmdCursorCreate { Bytes = cloneImg, Hotspot = hotSpot, Cursor = id });
SendCmd(new CmdCursorCreate(cloneImg, hotSpot, id));
return new CursorImpl(this, id, false);
}
private unsafe void WinThreadCursorCreate(CmdCursorCreate cmd)
{
using var img = cmd.Bytes;
var (img, (hotX, hotY), id) = cmd;
fixed (Rgba32* pixPtr = img.GetPixelSpan())
{
var surface = SDL.SDL_CreateSurfaceFrom(
img.Width,
img.Height,
SDL.SDL_PixelFormat.SDL_PIXELFORMAT_ABGR8888,
var surface = SDL_CreateRGBSurfaceWithFormatFrom(
(IntPtr)pixPtr,
sizeof(Rgba32) * img.Width);
img.Width, img.Height, 0,
sizeof(Rgba32) * img.Width,
SDL_PIXELFORMAT_RGBA8888);
var cursor = SDL.SDL_CreateColorCursor(surface, cmd.Hotspot.X, cmd.Hotspot.Y);
if (cursor == 0)
throw new InvalidOperationException("SDL_CreateColorCursor failed");
var cursor = SDL_CreateColorCursor(surface, hotX, hotY);
_winThreadCursors.Add(cmd.Cursor, new WinThreadCursorReg { Ptr = cursor });
_winThreadCursors.Add(id, new WinThreadCursorReg { Ptr = cursor });
SDL.SDL_DestroySurface(surface);
SDL_FreeSurface(surface);
}
img.Dispose();
}
public void CursorSet(WindowReg window, ICursor? cursor)
@@ -62,7 +62,7 @@ internal partial class Clyde
// SDL_SetCursor(NULL) does redraw, not reset.
cursor ??= CursorGetStandard(StandardCursorShape.Arrow);
var reg = (Sdl3WindowReg)window;
var reg = (Sdl2WindowReg)window;
if (reg.Cursor == cursor)
return;
@@ -74,7 +74,7 @@ internal partial class Clyde
throw new ObjectDisposedException(nameof(cursor));
reg.Cursor = impl;
SendCmd(new CmdWinCursorSet { Window = reg.Sdl3Window, Cursor = impl.Id });
SendCmd(new CmdWinCursorSet(reg.Sdl2Window, impl.Id));
}
private void WinThreadWinCursorSet(CmdWinCursorSet cmd)
@@ -83,22 +83,22 @@ internal partial class Clyde
var ptr = _winThreadCursors[cmd.Cursor].Ptr;
// TODO: multi-window??
SDL.SDL_SetCursor(ptr);
SDL_SetCursor(ptr);
}
private void InitCursors()
{
Add(StandardCursorShape.Arrow, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_DEFAULT);
Add(StandardCursorShape.IBeam, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_TEXT);
Add(StandardCursorShape.Crosshair, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_CROSSHAIR);
Add(StandardCursorShape.Hand, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_POINTER);
Add(StandardCursorShape.HResize, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_EW_RESIZE);
Add(StandardCursorShape.VResize, SDL.SDL_SystemCursor.SDL_SYSTEM_CURSOR_NS_RESIZE);
Add(StandardCursorShape.Arrow, SDL_SYSTEM_CURSOR_ARROW);
Add(StandardCursorShape.IBeam, SDL_SYSTEM_CURSOR_IBEAM);
Add(StandardCursorShape.Crosshair, SDL_SYSTEM_CURSOR_CROSSHAIR);
Add(StandardCursorShape.Hand, SDL_SYSTEM_CURSOR_HAND);
Add(StandardCursorShape.HResize, SDL_SYSTEM_CURSOR_SIZEWE);
Add(StandardCursorShape.VResize, SDL_SYSTEM_CURSOR_SIZENS);
void Add(StandardCursorShape shape, SDL.SDL_SystemCursor sysCursor)
void Add(StandardCursorShape shape, SDL_SystemCursor sysCursor)
{
var id = _clyde.AllocRid();
var cursor = SDL.SDL_CreateSystemCursor(sysCursor);
var cursor = SDL_CreateSystemCursor(sysCursor);
var impl = new CursorImpl(this, id, true);
@@ -107,21 +107,13 @@ internal partial class Clyde
}
}
private void WinThreadCursorDestroy(CmdCursorDestroy cmd)
{
if (!_winThreadCursors.TryGetValue(cmd.Cursor, out var cursor))
return;
SDL.SDL_DestroyCursor(cursor.Ptr);
}
private sealed class CursorImpl : ICursor
{
private readonly bool _standard;
public Sdl3WindowingImpl Owner { get; }
public Sdl2WindowingImpl Owner { get; }
public ClydeHandle Id { get; private set; }
public CursorImpl(Sdl3WindowingImpl clyde, ClydeHandle id, bool standard)
public CursorImpl(Sdl2WindowingImpl clyde, ClydeHandle id, bool standard)
{
_standard = standard;
Owner = clyde;
@@ -135,7 +127,7 @@ internal partial class Clyde
private void DisposeImpl()
{
Owner.SendCmd(new CmdCursorDestroy { Cursor = Id });
Owner.SendCmd(new CmdCursorDestroy(Id));
Id = default;
}
@@ -155,5 +147,9 @@ internal partial class Clyde
{
public nint Ptr;
}
private void WinThreadCursorDestroy(CmdCursorDestroy cmd)
{
}
}
}

View File

@@ -2,16 +2,18 @@
using System.Numerics;
using Robust.Client.Input;
using Robust.Shared.Map;
using SDL3;
using TerraFX.Interop.Windows;
using static SDL2.SDL;
using static SDL2.SDL.SDL_EventType;
using static SDL2.SDL.SDL_Keymod;
using static SDL2.SDL.SDL_WindowEventID;
using Key = Robust.Client.Input.Keyboard.Key;
using ET = SDL3.SDL.SDL_EventType;
using SDL_Keymod = SDL3.SDL.SDL_Keymod;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
private sealed partial class Sdl2WindowingImpl
{
public void ProcessEvents(bool single = false)
{
@@ -45,18 +47,15 @@ internal partial class Clyde
case EventWindowCreate wCreate:
FinishWindowCreate(wCreate);
break;
case EventWindowMisc ev:
ProcessEventWindowMisc(ev);
case EventWindow ev:
ProcessEventWindow(ev);
break;
case EventKey ev:
ProcessEventKey(ev);
break;
case EventWindowPixelSize ev:
case EventWindowSize ev:
ProcessEventWindowSize(ev);
break;
case EventWindowContentScale ev:
ProcessEventWindowContentScale(ev);
break;
case EventText ev:
ProcessEventText(ev);
break;
@@ -75,6 +74,9 @@ internal partial class Clyde
case EventMonitorSetup ev:
ProcessSetupMonitor(ev);
break;
case EventWindowsFakeV ev:
ProcessWindowsFakeV(ev);
break;
case EventKeyMapChanged:
ProcessKeyMapChanged();
break;
@@ -82,7 +84,7 @@ internal partial class Clyde
ProcessEventQuit();
break;
default:
_sawmill.Error($"Unknown SDL3 event type: {evb.GetType().Name}");
_sawmill.Error($"Unknown SDL2 event type: {evb.GetType().Name}");
break;
}
}
@@ -94,7 +96,7 @@ internal partial class Clyde
_clyde.SendCloseWindow(window, new WindowRequestClosedEventArgs(window.Handle));
}
private void ProcessEventWindowMisc(EventWindowMisc ev)
private void ProcessEventWindow(EventWindow ev)
{
var window = FindWindow(ev.WindowId);
if (window == null)
@@ -102,38 +104,33 @@ internal partial class Clyde
switch (ev.EventId)
{
case ET.SDL_EVENT_WINDOW_CLOSE_REQUESTED:
case SDL_WINDOWEVENT_CLOSE:
_clyde.SendCloseWindow(window, new WindowRequestClosedEventArgs(window.Handle));
break;
case ET.SDL_EVENT_WINDOW_MOUSE_ENTER:
case SDL_WINDOWEVENT_ENTER:
_clyde._currentHoveredWindow = window;
_clyde.SendMouseEnterLeave(new MouseEnterLeaveEventArgs(window.Handle, true));
break;
case ET.SDL_EVENT_WINDOW_MOUSE_LEAVE:
case SDL_WINDOWEVENT_LEAVE:
if (_clyde._currentHoveredWindow == window)
_clyde._currentHoveredWindow = null;
_clyde.SendMouseEnterLeave(new MouseEnterLeaveEventArgs(window.Handle, false));
break;
case ET.SDL_EVENT_WINDOW_MINIMIZED:
case SDL_WINDOWEVENT_MINIMIZED:
window.IsMinimized = true;
break;
case ET.SDL_EVENT_WINDOW_RESTORED:
case SDL_WINDOWEVENT_RESTORED:
window.IsMinimized = false;
break;
case ET.SDL_EVENT_WINDOW_FOCUS_GAINED:
case SDL_WINDOWEVENT_FOCUS_GAINED:
window.IsFocused = true;
_clyde.SendWindowFocus(new WindowFocusedEventArgs(true, window.Handle));
break;
case ET.SDL_EVENT_WINDOW_FOCUS_LOST:
case SDL_WINDOWEVENT_FOCUS_LOST:
window.IsFocused = false;
_clyde.SendWindowFocus(new WindowFocusedEventArgs(false, window.Handle));
break;
case ET.SDL_EVENT_WINDOW_MOVED:
window.WindowPos = (ev.Data1, ev.Data2);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
@@ -156,9 +153,10 @@ internal partial class Clyde
if (windowReg == null)
return;
var button = ConvertSdl3Button(ev.Button);
var mods = SDL_GetModState();
var button = ConvertSdl2Button(ev.Button);
var key = Mouse.MouseButtonToKey(button);
EmitKeyEvent(key, ev.Type, false, ev.Mods, 0);
EmitKeyEvent(key, ev.Type, false, mods, 0);
}
private void ProcessEventMouseMotion(EventMouseMotion ev)
@@ -168,7 +166,8 @@ internal partial class Clyde
return;
var newPos = new Vector2(ev.X, ev.Y) * windowReg.PixelRatio;
var delta = new Vector2(ev.XRel, ev.YRel);
// SDL2 does give us delta positions, but I'm worried about rounding errors thanks to DPI stuff.
var delta = newPos - windowReg.LastMousePos;
windowReg.LastMousePos = newPos;
_clyde._currentHoveredWindow = windowReg;
@@ -186,7 +185,7 @@ internal partial class Clyde
_clyde.SendTextEditing(new TextEditingEventArgs(ev.Text, ev.Start, ev.Length));
}
private void ProcessEventWindowSize(EventWindowPixelSize ev)
private void ProcessEventWindowSize(EventWindowSize ev)
{
var window = ev.WindowId;
var width = ev.Width;
@@ -206,31 +205,28 @@ internal partial class Clyde
return;
windowReg.PixelRatio = windowReg.FramebufferSize / (Vector2)windowReg.WindowSize;
var newScale = new Vector2(ev.XScale, ev.YScale);
if (!windowReg.WindowScale.Equals(newScale))
{
windowReg.WindowScale = newScale;
_clyde.SendWindowContentScaleChanged(new WindowContentScaleEventArgs(windowReg.Handle));
}
_clyde.SendWindowResized(windowReg, oldSize);
}
private void ProcessEventWindowContentScale(EventWindowContentScale ev)
{
var windowReg = FindWindow(ev.WindowId);
if (windowReg == null)
return;
windowReg.WindowScale = new Vector2(ev.Scale, ev.Scale);
_clyde.SendWindowContentScaleChanged(new WindowContentScaleEventArgs(windowReg.Handle));
}
private void ProcessEventKey(EventKey ev)
{
EmitKeyEvent(ConvertSdl3Scancode(ev.Scancode), ev.Type, ev.Repeat, ev.Mods, ev.Scancode);
EmitKeyEvent(ConvertSdl2Scancode(ev.Scancode), ev.Type, ev.Repeat, ev.Mods, ev.Scancode);
}
private void EmitKeyEvent(Key key, ET type, bool repeat, SDL.SDL_Keymod mods, SDL.SDL_Scancode scancode)
private void EmitKeyEvent(Key key, SDL_EventType type, bool repeat, SDL_Keymod mods, SDL_Scancode scancode)
{
var shift = (mods & SDL_Keymod.SDL_KMOD_SHIFT) != 0;
var alt = (mods & SDL_Keymod.SDL_KMOD_ALT) != 0;
var control = (mods & SDL_Keymod.SDL_KMOD_CTRL) != 0;
var system = (mods & SDL_Keymod.SDL_KMOD_GUI) != 0;
var shift = (mods & KMOD_SHIFT) != 0;
var alt = (mods & KMOD_ALT) != 0;
var control = (mods & KMOD_CTRL) != 0;
var system = (mods & KMOD_GUI) != 0;
var ev = new KeyEventArgs(
key,
@@ -240,17 +236,36 @@ internal partial class Clyde
switch (type)
{
case ET.SDL_EVENT_KEY_UP:
case ET.SDL_EVENT_MOUSE_BUTTON_UP:
case SDL_KEYUP:
case SDL_MOUSEBUTTONUP:
_clyde.SendKeyUp(ev);
break;
case ET.SDL_EVENT_KEY_DOWN:
case ET.SDL_EVENT_MOUSE_BUTTON_DOWN:
case SDL_KEYDOWN:
case SDL_MOUSEBUTTONDOWN:
_clyde.SendKeyDown(ev);
break;
}
}
private void ProcessWindowsFakeV(EventWindowsFakeV ev)
{
var type = (int)ev.Message switch
{
WM.WM_KEYUP => SDL_KEYUP,
WM.WM_KEYDOWN => SDL_KEYDOWN,
_ => throw new ArgumentOutOfRangeException()
};
var key = (int)ev.WParam switch
{
0x56 /* V */ => Key.V,
VK.VK_CONTROL => Key.Control,
_ => throw new ArgumentOutOfRangeException()
};
EmitKeyEvent(key, type, false, 0, 0);
}
private void ProcessKeyMapChanged()
{
_clyde.SendInputModeChanged();

View File

@@ -0,0 +1,224 @@
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using Robust.Client.Input;
using Robust.Shared;
using static SDL2.SDL;
using static SDL2.SDL.SDL_Scancode;
using Key = Robust.Client.Input.Keyboard.Key;
using Button = Robust.Client.Input.Mouse.Button;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl2WindowingImpl
{
// Indices are values of SDL_Scancode
private static readonly Key[] KeyMap;
private static readonly FrozenDictionary<Key, SDL_Scancode> KeyMapReverse;
private static readonly Button[] MouseButtonMap;
// TODO: to avoid having to ask the windowing thread, key names are cached.
private readonly Dictionary<Key, string> _printableKeyNameMap = new();
private void ReloadKeyMap()
{
// This may be ran concurrently from the windowing thread.
lock (_printableKeyNameMap)
{
_printableKeyNameMap.Clear();
// List of mappable keys from SDL2's source appears to be:
// entries in SDL_default_keymap that aren't an SDLK_ enum reference.
// (the actual logic is more nuanced, but it appears to match the above)
// Comes out to these two ranges:
for (var k = SDL_SCANCODE_A; k <= SDL_SCANCODE_0; k++)
{
CacheKey(k);
}
for (var k = SDL_SCANCODE_MINUS; k <= SDL_SCANCODE_SLASH; k++)
{
CacheKey(k);
}
void CacheKey(SDL_Scancode scancode)
{
var rKey = ConvertSdl2Scancode(scancode);
if (rKey == Key.Unknown)
return;
var name = SDL_GetKeyName(SDL_GetKeyFromScancode(scancode));
if (!string.IsNullOrEmpty(name))
_printableKeyNameMap.Add(rKey, name);
}
}
}
public string? KeyGetName(Key key)
{
lock (_printableKeyNameMap)
{
if (_printableKeyNameMap.TryGetValue(key, out var name))
return name;
return null;
}
}
internal static Key ConvertSdl2Scancode(SDL_Scancode scancode)
{
return KeyMap[(int) scancode];
}
public static Button ConvertSdl2Button(int button)
{
return MouseButtonMap[button];
}
static Sdl2WindowingImpl()
{
MouseButtonMap = new Button[6];
MouseButtonMap[SDL_BUTTON_LEFT] = Button.Left;
MouseButtonMap[SDL_BUTTON_RIGHT] = Button.Right;
MouseButtonMap[SDL_BUTTON_MIDDLE] = Button.Middle;
MouseButtonMap[SDL_BUTTON_X1] = Button.Button4;
MouseButtonMap[SDL_BUTTON_X2] = Button.Button5;
KeyMap = new Key[(int) SDL_NUM_SCANCODES];
MapKey(SDL_SCANCODE_A, Key.A);
MapKey(SDL_SCANCODE_B, Key.B);
MapKey(SDL_SCANCODE_C, Key.C);
MapKey(SDL_SCANCODE_D, Key.D);
MapKey(SDL_SCANCODE_E, Key.E);
MapKey(SDL_SCANCODE_F, Key.F);
MapKey(SDL_SCANCODE_G, Key.G);
MapKey(SDL_SCANCODE_H, Key.H);
MapKey(SDL_SCANCODE_I, Key.I);
MapKey(SDL_SCANCODE_J, Key.J);
MapKey(SDL_SCANCODE_K, Key.K);
MapKey(SDL_SCANCODE_L, Key.L);
MapKey(SDL_SCANCODE_M, Key.M);
MapKey(SDL_SCANCODE_N, Key.N);
MapKey(SDL_SCANCODE_O, Key.O);
MapKey(SDL_SCANCODE_P, Key.P);
MapKey(SDL_SCANCODE_Q, Key.Q);
MapKey(SDL_SCANCODE_R, Key.R);
MapKey(SDL_SCANCODE_S, Key.S);
MapKey(SDL_SCANCODE_T, Key.T);
MapKey(SDL_SCANCODE_U, Key.U);
MapKey(SDL_SCANCODE_V, Key.V);
MapKey(SDL_SCANCODE_W, Key.W);
MapKey(SDL_SCANCODE_X, Key.X);
MapKey(SDL_SCANCODE_Y, Key.Y);
MapKey(SDL_SCANCODE_Z, Key.Z);
MapKey(SDL_SCANCODE_0, Key.Num0);
MapKey(SDL_SCANCODE_1, Key.Num1);
MapKey(SDL_SCANCODE_2, Key.Num2);
MapKey(SDL_SCANCODE_3, Key.Num3);
MapKey(SDL_SCANCODE_4, Key.Num4);
MapKey(SDL_SCANCODE_5, Key.Num5);
MapKey(SDL_SCANCODE_6, Key.Num6);
MapKey(SDL_SCANCODE_7, Key.Num7);
MapKey(SDL_SCANCODE_8, Key.Num8);
MapKey(SDL_SCANCODE_9, Key.Num9);
MapKey(SDL_SCANCODE_KP_0, Key.NumpadNum0);
MapKey(SDL_SCANCODE_KP_1, Key.NumpadNum1);
MapKey(SDL_SCANCODE_KP_2, Key.NumpadNum2);
MapKey(SDL_SCANCODE_KP_3, Key.NumpadNum3);
MapKey(SDL_SCANCODE_KP_4, Key.NumpadNum4);
MapKey(SDL_SCANCODE_KP_5, Key.NumpadNum5);
MapKey(SDL_SCANCODE_KP_6, Key.NumpadNum6);
MapKey(SDL_SCANCODE_KP_7, Key.NumpadNum7);
MapKey(SDL_SCANCODE_KP_8, Key.NumpadNum8);
MapKey(SDL_SCANCODE_KP_9, Key.NumpadNum9);
MapKey(SDL_SCANCODE_ESCAPE, Key.Escape);
MapKey(SDL_SCANCODE_LCTRL, Key.Control);
MapKey(SDL_SCANCODE_RCTRL, Key.Control);
MapKey(SDL_SCANCODE_RSHIFT, Key.Shift);
MapKey(SDL_SCANCODE_LSHIFT, Key.Shift);
MapKey(SDL_SCANCODE_LALT, Key.Alt);
MapKey(SDL_SCANCODE_RALT, Key.Alt);
MapKey(SDL_SCANCODE_LGUI, Key.LSystem);
MapKey(SDL_SCANCODE_RGUI, Key.RSystem);
MapKey(SDL_SCANCODE_MENU, Key.Menu);
MapKey(SDL_SCANCODE_LEFTBRACKET, Key.LBracket);
MapKey(SDL_SCANCODE_RIGHTBRACKET, Key.RBracket);
MapKey(SDL_SCANCODE_SEMICOLON, Key.SemiColon);
MapKey(SDL_SCANCODE_COMMA, Key.Comma);
MapKey(SDL_SCANCODE_PERIOD, Key.Period);
MapKey(SDL_SCANCODE_APOSTROPHE, Key.Apostrophe);
MapKey(SDL_SCANCODE_SLASH, Key.Slash);
MapKey(SDL_SCANCODE_BACKSLASH, Key.BackSlash);
MapKey(SDL_SCANCODE_GRAVE, Key.Tilde);
MapKey(SDL_SCANCODE_EQUALS, Key.Equal);
MapKey(SDL_SCANCODE_SPACE, Key.Space);
MapKey(SDL_SCANCODE_RETURN, Key.Return);
MapKey(SDL_SCANCODE_KP_ENTER, Key.NumpadEnter);
MapKey(SDL_SCANCODE_BACKSPACE, Key.BackSpace);
MapKey(SDL_SCANCODE_TAB, Key.Tab);
MapKey(SDL_SCANCODE_PAGEUP, Key.PageUp);
MapKey(SDL_SCANCODE_PAGEDOWN, Key.PageDown);
MapKey(SDL_SCANCODE_END, Key.End);
MapKey(SDL_SCANCODE_HOME, Key.Home);
MapKey(SDL_SCANCODE_INSERT, Key.Insert);
MapKey(SDL_SCANCODE_DELETE, Key.Delete);
MapKey(SDL_SCANCODE_MINUS, Key.Minus);
MapKey(SDL_SCANCODE_KP_PLUS, Key.NumpadAdd);
MapKey(SDL_SCANCODE_KP_MINUS, Key.NumpadSubtract);
MapKey(SDL_SCANCODE_KP_DIVIDE, Key.NumpadDivide);
MapKey(SDL_SCANCODE_KP_MULTIPLY, Key.NumpadMultiply);
MapKey(SDL_SCANCODE_KP_DECIMAL, Key.NumpadDecimal);
MapKey(SDL_SCANCODE_LEFT, Key.Left);
MapKey(SDL_SCANCODE_RIGHT, Key.Right);
MapKey(SDL_SCANCODE_UP, Key.Up);
MapKey(SDL_SCANCODE_DOWN, Key.Down);
MapKey(SDL_SCANCODE_F1, Key.F1);
MapKey(SDL_SCANCODE_F2, Key.F2);
MapKey(SDL_SCANCODE_F3, Key.F3);
MapKey(SDL_SCANCODE_F4, Key.F4);
MapKey(SDL_SCANCODE_F5, Key.F5);
MapKey(SDL_SCANCODE_F6, Key.F6);
MapKey(SDL_SCANCODE_F7, Key.F7);
MapKey(SDL_SCANCODE_F8, Key.F8);
MapKey(SDL_SCANCODE_F9, Key.F9);
MapKey(SDL_SCANCODE_F10, Key.F10);
MapKey(SDL_SCANCODE_F11, Key.F11);
MapKey(SDL_SCANCODE_F12, Key.F12);
MapKey(SDL_SCANCODE_F13, Key.F13);
MapKey(SDL_SCANCODE_F14, Key.F14);
MapKey(SDL_SCANCODE_F15, Key.F15);
MapKey(SDL_SCANCODE_F16, Key.F16);
MapKey(SDL_SCANCODE_F17, Key.F17);
MapKey(SDL_SCANCODE_F18, Key.F18);
MapKey(SDL_SCANCODE_F19, Key.F19);
MapKey(SDL_SCANCODE_F20, Key.F20);
MapKey(SDL_SCANCODE_F21, Key.F21);
MapKey(SDL_SCANCODE_F22, Key.F22);
MapKey(SDL_SCANCODE_F23, Key.F23);
MapKey(SDL_SCANCODE_F24, Key.F24);
MapKey(SDL_SCANCODE_PAUSE, Key.Pause);
var keyMapReverse = new Dictionary<Key, SDL_Scancode>();
for (var code = 0; code < KeyMap.Length; code++)
{
var key = KeyMap[code];
if (key != Key.Unknown)
keyMapReverse[key] = (SDL_Scancode) code;
}
KeyMapReverse = keyMapReverse.ToFrozenDictionary();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void MapKey(SDL_Scancode code, Key key)
{
KeyMap[(int)code] = key;
}
}
}
}

View File

@@ -0,0 +1,133 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using SDL2;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl2WindowingImpl
{
// NOTE: SDL2 calls them "displays". GLFW calls them monitors. GLFW's is the one I'm going with.
// Can't use ClydeHandle because it's not thread safe to allocate.
private int _nextMonitorId = 1;
private readonly Dictionary<int, WinThreadMonitorReg> _winThreadMonitors = new();
private readonly Dictionary<int, Sdl2MonitorReg> _monitors = new();
private void InitMonitors()
{
var numDisplays = SDL.SDL_GetNumVideoDisplays();
for (var i = 0; i < numDisplays; i++)
{
// SDL.SDL_GetDisplayDPI(i, out var ddpi, out var hdpi, out var vdpi);
// _sawmill.Info($"[{i}] {ddpi} {hdpi} {vdpi}");
WinThreadSetupMonitor(i);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void WinThreadSetupMonitor(int displayIdx)
{
var id = _nextMonitorId++;
var name = SDL.SDL_GetDisplayName(displayIdx);
var modeCount = SDL.SDL_GetNumDisplayModes(displayIdx);
SDL.SDL_GetCurrentDisplayMode(displayIdx, out var curMode);
var modes = new VideoMode[modeCount];
for (var i = 0; i < modes.Length; i++)
{
SDL.SDL_GetDisplayMode(displayIdx, i, out var mode);
modes[i] = ConvertVideoMode(mode);
}
_winThreadMonitors.Add(id, new WinThreadMonitorReg { Id = id, DisplayIdx = displayIdx });
SendEvent(new EventMonitorSetup(id, name, ConvertVideoMode(curMode), modes));
if (displayIdx == 0)
_clyde._primaryMonitorId = id;
}
private static VideoMode ConvertVideoMode(in SDL.SDL_DisplayMode mode)
{
return new()
{
Width = (ushort)mode.w,
Height = (ushort)mode.h,
RefreshRate = (ushort)mode.refresh_rate,
// TODO: set bits count based on format (I'm lazy)
RedBits = 8,
GreenBits = 8,
BlueBits = 8,
};
}
private void ProcessSetupMonitor(EventMonitorSetup ev)
{
var impl = new MonitorHandle(
ev.Id,
ev.Name,
(ev.CurrentMode.Width, ev.CurrentMode.Height),
ev.CurrentMode.RefreshRate,
ev.AllModes);
_clyde._monitorHandles.Add(ev.Id, impl);
_monitors[ev.Id] = new Sdl2MonitorReg
{
Id = ev.Id,
Handle = impl
};
}
private void WinThreadDestroyMonitor(int displayIdx)
{
var monitorId = 0;
foreach (var (id, monitorReg) in _winThreadMonitors)
{
if (monitorReg.DisplayIdx == displayIdx)
{
monitorId = id;
break;
}
}
if (monitorId == 0)
return;
// So SDL2 doesn't have a very nice indexing system for monitors like GLFW does.
// This means that, when a monitor is disconnected, all monitors *after* it get shifted down one slot.
// Now, this happens *after* the event is fired, to make matters worse.
// So we're basically trying to match unspecified SDL2 internals here. Great.
_winThreadMonitors.Remove(monitorId);
foreach (var (_, reg) in _winThreadMonitors)
{
if (reg.DisplayIdx > displayIdx)
reg.DisplayIdx -= 1;
}
SendEvent(new EventMonitorDestroy(monitorId));
}
private void ProcessEventDestroyMonitor(EventMonitorDestroy ev)
{
_monitors.Remove(ev.Id);
_clyde._monitorHandles.Remove(ev.Id);
}
private sealed class Sdl2MonitorReg : MonitorReg
{
public int Id;
}
private sealed class WinThreadMonitorReg
{
public int Id;
public int DisplayIdx;
}
}
}

View File

@@ -0,0 +1,316 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Robust.Shared.Maths;
using TerraFX.Interop.Windows;
using static SDL2.SDL;
using static SDL2.SDL.SDL_EventType;
using static SDL2.SDL.SDL_SYSWM_TYPE;
using static SDL2.SDL.SDL_WindowEventID;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl2WindowingImpl
{
[UnmanagedCallersOnly(CallConvs = new []{typeof(CallConvCdecl)})]
private static unsafe int EventWatch(void* userdata, SDL_Event* sdlevent)
{
var obj = (Sdl2WindowingImpl) GCHandle.FromIntPtr((IntPtr)userdata).Target!;
ref readonly var ev = ref *sdlevent;
obj.ProcessSdl2Event(in ev);
return 0;
}
private void ProcessSdl2Event(in SDL_Event ev)
{
switch (ev.type)
{
case SDL_WINDOWEVENT:
ProcessSdl2EventWindow(in ev.window);
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
ProcessSdl2KeyEvent(in ev.key);
break;
case SDL_TEXTINPUT:
ProcessSdl2EventTextInput(in ev.text);
break;
case SDL_TEXTEDITING:
ProcessSdl2EventTextEditing(in ev.edit);
break;
case SDL_KEYMAPCHANGED:
ProcessSdl2EventKeyMapChanged();
break;
case SDL_TEXTEDITING_EXT:
ProcessSdl2EventTextEditingExt(in ev.editExt);
break;
case SDL_MOUSEMOTION:
ProcessSdl2EventMouseMotion(in ev.motion);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
ProcessSdl2EventMouseButton(in ev.button);
break;
case SDL_MOUSEWHEEL:
ProcessSdl2EventMouseWheel(in ev.wheel);
break;
case SDL_DISPLAYEVENT:
ProcessSdl2EventDisplay(in ev.display);
break;
case SDL_SYSWMEVENT:
ProcessSdl2EventSysWM(in ev.syswm);
break;
case SDL_QUIT:
ProcessSdl2EventQuit();
break;
}
}
private void ProcessSdl2EventQuit()
{
SendEvent(new EventQuit());
}
private void ProcessSdl2EventDisplay(in SDL_DisplayEvent evDisplay)
{
switch (evDisplay.displayEvent)
{
case SDL_DisplayEventID.SDL_DISPLAYEVENT_CONNECTED:
WinThreadSetupMonitor((int) evDisplay.display);
break;
case SDL_DisplayEventID.SDL_DISPLAYEVENT_DISCONNECTED:
WinThreadDestroyMonitor((int) evDisplay.display);
break;
}
}
private void ProcessSdl2EventMouseWheel(in SDL_MouseWheelEvent ev)
{
SendEvent(new EventWheel(ev.windowID, ev.preciseX, ev.preciseY));
}
private void ProcessSdl2EventMouseButton(in SDL_MouseButtonEvent ev)
{
SendEvent(new EventMouseButton(ev.windowID, ev.type, ev.button));
}
private void ProcessSdl2EventMouseMotion(in SDL_MouseMotionEvent ev)
{
// _sawmill.Info($"{evMotion.x}, {evMotion.y}, {evMotion.xrel}, {evMotion.yrel}");
SendEvent(new EventMouseMotion(ev.windowID, ev.x, ev.y, ev.xrel, ev.yrel));
}
private unsafe void ProcessSdl2EventTextInput(in SDL_TextInputEvent ev)
{
fixed (byte* text = ev.text)
{
var str = Marshal.PtrToStringUTF8((IntPtr)text) ?? "";
// _logManager.GetSawmill("ime").Debug($"Input: {str}");
SendEvent(new EventText(ev.windowID, str));
}
}
private unsafe void ProcessSdl2EventTextEditing(in SDL_TextEditingEvent ev)
{
fixed (byte* text = ev.text)
{
SendTextEditing(ev.windowID, text, ev.start, ev.length);
}
}
private unsafe void ProcessSdl2EventTextEditingExt(in SDL_TextEditingExtEvent ev)
{
SendTextEditing(ev.windowID, (byte*) ev.text, ev.start, ev.length);
SDL_free(ev.text);
}
private unsafe void SendTextEditing(uint window, byte* text, int start, int length)
{
var str = Marshal.PtrToStringUTF8((nint) text) ?? "";
// _logManager.GetSawmill("ime").Debug($"Editing: '{str}', start: {start}, len: {length}");
SendEvent(new EventTextEditing(window, str, start, length));
}
private void ProcessSdl2EventKeyMapChanged()
{
ReloadKeyMap();
SendEvent(new EventKeyMapChanged());
}
private void ProcessSdl2KeyEvent(in SDL_KeyboardEvent ev)
{
SendEvent(new EventKey(
ev.windowID,
ev.keysym.scancode,
ev.type,
ev.repeat != 0,
ev.keysym.mod));
}
private void ProcessSdl2EventWindow(in SDL_WindowEvent ev)
{
var window = SDL_GetWindowFromID(ev.windowID);
switch (ev.windowEvent)
{
case SDL_WINDOWEVENT_SIZE_CHANGED:
var width = ev.data1;
var height = ev.data2;
SDL_GetWindowSizeInPixels(window, out var fbW, out var fbH);
var (xScale, yScale) = GetWindowScale(window);
_sawmill.Debug($"{width}x{height}, {fbW}x{fbH}, {xScale}x{yScale}");
SendEvent(new EventWindowSize(ev.windowID, width, height, fbW, fbH, xScale, yScale));
break;
default:
SendEvent(new EventWindow(ev.windowID, ev.windowEvent));
break;
}
}
// ReSharper disable once InconsistentNaming
private unsafe void ProcessSdl2EventSysWM(in SDL_SysWMEvent ev)
{
ref readonly var sysWmMessage = ref *(SDL_SysWMmsg*)ev.msg;
if (sysWmMessage.subsystem != SDL_SYSWM_WINDOWS)
return;
ref readonly var winMessage = ref *(SDL_SysWMmsgWin32*)ev.msg;
if (winMessage.msg is WM.WM_KEYDOWN or WM.WM_KEYUP)
{
TryWin32VirtualVKey(in winMessage);
}
}
private void TryWin32VirtualVKey(in SDL_SysWMmsgWin32 msg)
{
// Workaround for https://github.com/ocornut/imgui/issues/2977
// This is gonna bite me in the ass if SDL2 ever fixes this upstream, isn't it...
// (I spent disproportionate amounts of effort on this).
// Code for V key.
if ((int)msg.wParam is not (0x56 or VK.VK_CONTROL))
return;
var scanCode = (msg.lParam >> 16) & 0xFF;
if (scanCode != 0)
return;
SendEvent(new EventWindowsFakeV(msg.hwnd, msg.msg, msg.wParam));
}
private abstract record EventBase;
private record EventWindowCreate(
Sdl2WindowCreateResult Result,
TaskCompletionSource<Sdl2WindowCreateResult> Tcs
) : EventBase;
private record EventKey(
uint WindowId,
SDL_Scancode Scancode,
SDL_EventType Type,
bool Repeat,
SDL_Keymod Mods
) : EventBase;
private record EventMouseMotion(
uint WindowId,
int X, int Y,
int XRel, int YRel
) : EventBase;
private record EventMouseButton(
uint WindowId,
SDL_EventType Type,
byte Button
) : EventBase;
private record EventText(
uint WindowId,
string Text
) : EventBase;
private record EventTextEditing(
uint WindowId,
string Text,
int Start,
int Length
) : EventBase;
private record EventWindowSize(
uint WindowId,
int Width,
int Height,
int FramebufferWidth,
int FramebufferHeight,
float XScale,
float YScale
) : EventBase;
private record EventWheel(
uint WindowId,
float XOffset,
float YOffset
) : EventBase;
// SDL_WindowEvents that don't have special handling like size.
private record EventWindow(
uint WindowId,
SDL_WindowEventID EventId
) : EventBase;
private record EventMonitorSetup
(
int Id,
string Name,
VideoMode CurrentMode,
VideoMode[] AllModes
) : EventBase;
private record EventMonitorDestroy
(
int Id
) : EventBase;
private record EventWindowsFakeV(HWND Window,
uint Message, WPARAM WParam) : EventBase;
private record EventKeyMapChanged : EventBase;
private record EventQuit : EventBase;
[StructLayout(LayoutKind.Sequential)]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "IdentifierTypo")]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
private struct SDL_SysWMmsg
{
public SDL_version version;
public SDL_SYSWM_TYPE subsystem;
}
[StructLayout(LayoutKind.Sequential)]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "IdentifierTypo")]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
private struct SDL_SysWMmsgWin32
{
public SDL_version version;
public SDL_SYSWM_TYPE subsystem;
public HWND hwnd;
public uint msg;
public WPARAM wParam;
public LPARAM lParam;
}
}
}

View File

@@ -4,15 +4,15 @@ using System.Threading.Channels;
using System.Threading.Tasks;
using Robust.Shared;
using Robust.Shared.Maths;
using SDL3;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using static SDL2.SDL;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
private sealed partial class Sdl2WindowingImpl
{
private bool _windowingRunning;
private ChannelWriter<CmdBase> _cmdWriter = default!;
@@ -29,34 +29,34 @@ internal partial class Clyde
while (_windowingRunning)
{
var res = SDL.SDL_WaitEventRef(ref Unsafe.NullRef<SDL.SDL_Event>());
if (!res)
var res = SDL_WaitEvent(out Unsafe.NullRef<SDL_Event>());
if (res == 0)
{
_sawmill.Error("Error while waiting on SDL3 events: {error}", SDL.SDL_GetError());
_sawmill.Error("Error while waiting on SDL2 events: {error}", SDL_GetError());
continue; // Assume it's a transient failure?
}
while (SDL.SDL_PollEvent(out _))
while (SDL_PollEvent(out _) == 1)
{
// We let callbacks process all events because of stuff like resizing.
}
while (_cmdReader.TryRead(out var cmd) && _windowingRunning)
{
ProcessSdl3Cmd(cmd);
ProcessSdl2Cmd(cmd);
}
}
}
public void PollEvents()
{
while (SDL.SDL_PollEvent(out _))
while (SDL_PollEvent(out _) == 1)
{
// We let callbacks process all events because of stuff like resizing.
}
}
private void ProcessSdl3Cmd(CmdBase cmdb)
private void ProcessSdl2Cmd(CmdBase cmdb)
{
switch (cmdb)
{
@@ -113,24 +113,20 @@ internal partial class Clyde
WinThreadWinCursorSet(cmd);
break;
case CmdWinWinSetFullscreen cmd:
WinThreadWinSetFullscreen(cmd);
break;
case CmdWinSetWindowed cmd:
WinThreadWinSetWindowed(cmd);
case CmdWinWinSetMode cmd:
WinThreadWinSetMode(cmd);
break;
case CmdTextInputSetRect cmd:
WinThreadSetTextInputRect(cmd);
break;
case CmdTextInputStart cmd:
WinThreadStartTextInput(cmd);
case CmdTextInputStart:
WinThreadStartTextInput();
break;
case CmdTextInputStop cmd:
WinThreadStopTextInput(cmd);
case CmdTextInputStop:
WinThreadStopTextInput();
break;
}
}
@@ -175,25 +171,25 @@ internal partial class Clyde
_eventWriter = eventChannel.Writer;
}
private void SendCmd(CmdBase cmd)
private unsafe void SendCmd(CmdBase cmd)
{
if (_clyde._threadWindowApi)
{
_cmdWriter.TryWrite(cmd);
SDL.SDL_Event ev = default;
ev.type = _sdlEventWakeup;
SDL_Event ev = default;
ev.type = (SDL_EventType)_sdlEventWakeup;
// Post empty event to unstuck WaitEvents if necessary.
// This self-registered event type is ignored by the winthread, but it'll still wake it up.
// This can fail if the event queue is full.
// That's not really a problem since in that case something else will be sure to wake the thread up anyways.
// NOTE: have to avoid using PushEvents since that invokes callbacks which causes a deadlock.
SDL.SDL_PeepEvents(new Span<SDL.SDL_Event>(ref ev), 1, SDL.SDL_EventAction.SDL_ADDEVENT, ev.type, ev.type);
SDL_PeepEvents(&ev, 1, SDL_eventaction.SDL_ADDEVENT, ev.type, ev.type);
}
else
{
ProcessSdl3Cmd(cmd);
ProcessSdl2Cmd(cmd);
}
}
@@ -215,119 +211,93 @@ internal partial class Clyde
}
private abstract class CmdBase;
private abstract record CmdBase;
private sealed class CmdTerminate : CmdBase;
private sealed record CmdTerminate : CmdBase;
private sealed class CmdWinCreate : CmdBase
{
public required GLContextSpec? GLSpec;
public required WindowCreateParameters Parameters;
public required nint ShareWindow;
public required nint ShareContext;
public required nint OwnerWindow;
public required TaskCompletionSource<Sdl3WindowCreateResult> Tcs;
}
private sealed record CmdWinCreate(
GLContextSpec? GLSpec,
WindowCreateParameters Parameters,
nint ShareWindow,
nint ShareContext,
nint OwnerWindow,
TaskCompletionSource<Sdl2WindowCreateResult> Tcs
) : CmdBase;
private sealed class CmdWinDestroy : CmdBase
{
public nint Window;
public bool HadOwner;
}
private sealed record CmdWinDestroy(
nint Window,
bool HadOwner
) : CmdBase;
private sealed class Sdl3WindowCreateResult
{
public Sdl3WindowReg? Reg;
public string? Error;
}
private sealed record Sdl2WindowCreateResult(
Sdl2WindowReg? Reg,
string? Error
);
private sealed class CmdRunAction : CmdBase
{
public required Action Action;
}
private sealed record CmdRunAction(
Action Action
) : CmdBase;
private sealed class CmdSetClipboard : CmdBase
{
public required string Text;
}
private sealed record CmdSetClipboard(
string Text
) : CmdBase;
private sealed class CmdGetClipboard : CmdBase
{
public required TaskCompletionSource<string> Tcs;
}
private sealed record CmdGetClipboard(
TaskCompletionSource<string> Tcs
) : CmdBase;
private sealed class CmdWinRequestAttention : CmdBase
{
public nint Window;
}
private sealed record CmdWinRequestAttention(
nint Window
) : CmdBase;
private sealed class CmdWinSetSize : CmdBase
{
public nint Window;
public int W;
public int H;
}
private sealed record CmdWinSetSize(
nint Window,
int W, int H
) : CmdBase;
private sealed class CmdWinSetVisible : CmdBase
{
public nint Window;
public bool Visible;
}
private sealed record CmdWinSetVisible(
nint Window,
bool Visible
) : CmdBase;
private sealed class CmdWinSetTitle : CmdBase
{
public nint Window;
public required string Title;
}
private sealed record CmdWinSetTitle(
nint Window,
string Title
) : CmdBase;
private sealed class CmdCursorCreate : CmdBase
{
public required Image<Rgba32> Bytes;
public Vector2i Hotspot;
public ClydeHandle Cursor;
}
private sealed record CmdCursorCreate(
Image<Rgba32> Bytes,
Vector2i Hotspot,
ClydeHandle Cursor
) : CmdBase;
private sealed class CmdCursorDestroy : CmdBase
{
public ClydeHandle Cursor;
}
private sealed record CmdCursorDestroy(
ClydeHandle Cursor
) : CmdBase;
private sealed class CmdWinCursorSet : CmdBase
{
public nint Window;
public ClydeHandle Cursor;
}
private sealed record CmdWinCursorSet(
nint Window,
ClydeHandle Cursor
) : CmdBase;
private sealed class CmdWinWinSetFullscreen : CmdBase
{
public nint Window;
}
private sealed class CmdWinSetWindowed : CmdBase
{
public nint Window;
public int Width;
public int Height;
public int PosX;
public int PosY;
}
private sealed record CmdWinWinSetMode(
nint Window,
WindowMode Mode
) : CmdBase;
// IME
private sealed class CmdTextInputStart : CmdBase
private sealed record CmdTextInputStart : CmdBase
{
public nint Window;
public static readonly CmdTextInputStart Instance = new();
}
private sealed class CmdTextInputStop : CmdBase
private sealed record CmdTextInputStop : CmdBase
{
public nint Window;
public static readonly CmdTextInputStop Instance = new();
}
private sealed class CmdTextInputSetRect : CmdBase
{
public nint Window;
public SDL.SDL_Rect Rect;
public int Cursor;
}
private sealed record CmdTextInputSetRect(
SDL_Rect Rect
) : CmdBase;
}
}

View File

@@ -0,0 +1,586 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
using static SDL2.SDL;
using static SDL2.SDL.SDL_bool;
using static SDL2.SDL.SDL_FlashOperation;
using static SDL2.SDL.SDL_GLattr;
using static SDL2.SDL.SDL_GLcontext;
using static SDL2.SDL.SDL_GLprofile;
using static SDL2.SDL.SDL_SYSWM_TYPE;
using static SDL2.SDL.SDL_WindowFlags;
using BOOL = TerraFX.Interop.Windows.BOOL;
using HWND = TerraFX.Interop.Windows.HWND;
using GWLP = TerraFX.Interop.Windows.GWLP;
using Windows = TerraFX.Interop.Windows.Windows;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl2WindowingImpl
{
private int _nextWindowId = 1;
public (WindowReg?, string? error) WindowCreate(
GLContextSpec? spec,
WindowCreateParameters parameters,
WindowReg? share,
WindowReg? owner)
{
nint shareWindow = 0;
nint shareContext = 0;
if (share is Sdl2WindowReg shareReg)
{
shareWindow = shareReg.Sdl2Window;
shareContext = shareReg.GlContext;
}
nint ownerPtr = 0;
if (owner is Sdl2WindowReg ownerReg)
ownerPtr = ownerReg.Sdl2Window;
var task = SharedWindowCreate(spec, parameters, shareWindow, shareContext, ownerPtr);
// Block the main thread (to avoid stuff like texture uploads being problematic).
WaitWindowCreate(task);
#pragma warning disable RA0004
// Block above ensured task is done, this is safe.
var (reg, error) = task.Result;
#pragma warning restore RA0004
if (reg != null)
{
reg.Owner = reg.Handle;
}
return (reg, error);
}
private void WaitWindowCreate(Task<Sdl2WindowCreateResult> windowTask)
{
while (!windowTask.IsCompleted)
{
// Keep processing events until the window task gives either an error or success.
WaitEvents();
ProcessEvents(single: true);
}
}
private Task<Sdl2WindowCreateResult> SharedWindowCreate(
GLContextSpec? glSpec,
WindowCreateParameters parameters,
nint shareWindow,
nint shareContext,
nint owner)
{
//
// IF YOU'RE WONDERING WHY THIS IS TASK-BASED:
// I originally wanted this to be async so we could avoid blocking the main thread
// while the OS takes its stupid 100~ms just to initialize a fucking GL context.
// This doesn't *work* because
// we have to release the GL context while the shared context is being created.
// (at least on WGL, I didn't test other platforms and I don't care to.)
// Not worth it to avoid a main thread blockage by allowing Clyde to temporarily release the GL context,
// because rendering would be locked up *anyways*.
//
// Basically what I'm saying is that everything about OpenGL is a fucking mistake
// and I should get on either Veldrid or Vulkan some time.
// Probably Veldrid tbh.
//
// Yes we ping-pong this TCS through the window thread and back, deal with it.
var tcs = new TaskCompletionSource<Sdl2WindowCreateResult>();
SendCmd(new CmdWinCreate(glSpec, parameters, shareWindow, shareContext, owner, tcs));
return tcs.Task;
}
private static void FinishWindowCreate(EventWindowCreate ev)
{
var (res, tcs) = ev;
tcs.TrySetResult(res);
}
private void WinThreadWinCreate(CmdWinCreate cmd)
{
var (glSpec, parameters, shareWindow, shareContext, owner, tcs) = cmd;
var (window, context) = CreateSdl2WindowForRenderer(glSpec, parameters, shareWindow, shareContext, owner);
if (window == 0)
{
var err = SDL_GetError();
SendEvent(new EventWindowCreate(new Sdl2WindowCreateResult(null, err), tcs));
return;
}
// We can't invoke the TCS directly from the windowing thread because:
// * it'd hit the synchronization context,
// which would make (blocking) main window init more annoying.
// * it'd not be synchronized to other incoming window events correctly which might be icky.
// So we send the TCS back to the game thread
// which processes events in the correct order and has better control of stuff during init.
var reg = WinThreadSetupWindow(window, context);
SendEvent(new EventWindowCreate(new Sdl2WindowCreateResult(reg, null), tcs));
}
private static void WinThreadWinDestroy(CmdWinDestroy cmd)
{
if (OperatingSystem.IsWindows() && cmd.HadOwner)
{
// On Windows, closing the child window causes the owner to be minimized, apparently.
// Clear owner on close to avoid this.
SDL_SysWMinfo wmInfo = default;
SDL_VERSION(out wmInfo.version);
if (SDL_GetWindowWMInfo(cmd.Window, ref wmInfo) == SDL_TRUE && wmInfo.subsystem == SDL_SYSWM_WINDOWS)
{
var hWnd = (HWND)wmInfo.info.win.window;
DebugTools.Assert(hWnd != HWND.NULL);
Windows.SetWindowLongPtrW(
hWnd,
GWLP.GWLP_HWNDPARENT,
0);
}
}
SDL_DestroyWindow(cmd.Window);
}
private (nint window, nint context) CreateSdl2WindowForRenderer(
GLContextSpec? spec,
WindowCreateParameters parameters,
nint shareWindow,
nint shareContext,
nint ownerWindow)
{
var windowFlags = SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE;
if (spec is { } s)
{
windowFlags |= SDL_WINDOW_OPENGL;
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, s.Profile == GLContextProfile.Es ? 0 : 1);
SDL_GLcontext ctxFlags = 0;
#if DEBUG
ctxFlags |= SDL_GL_CONTEXT_DEBUG_FLAG;
#endif
if (s.Profile == GLContextProfile.Core)
ctxFlags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (int)ctxFlags);
if (shareContext != 0)
{
SDL_GL_MakeCurrent(shareWindow, shareContext);
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
}
else
{
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
}
var profile = s.Profile switch
{
GLContextProfile.Compatibility => SDL_GL_CONTEXT_PROFILE_COMPATIBILITY,
GLContextProfile.Core => SDL_GL_CONTEXT_PROFILE_CORE,
GLContextProfile.Es => SDL_GL_CONTEXT_PROFILE_ES,
_ => SDL_GL_CONTEXT_PROFILE_COMPATIBILITY,
};
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile);
SDL_SetHint("SDL_OPENGL_ES_DRIVER", s.CreationApi == GLContextCreationApi.Egl ? "1" : "0");
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, s.Major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, s.Minor);
if (s.CreationApi == GLContextCreationApi.Egl)
WsiShared.EnsureEglAvailable();
}
if (OperatingSystem.IsMacOS())
{
windowFlags |= SDL_WINDOW_ALLOW_HIGHDPI;
}
if (parameters.Fullscreen)
{
windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
}
nint window = SDL_CreateWindow(
"",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
parameters.Width, parameters.Height,
windowFlags);
if (window == 0)
return default;
nint glContext = SDL_GL_CreateContext(window);
if (glContext == 0)
{
SDL_DestroyWindow(window);
return default;
}
// TODO: Monitors, window maximize.
// TODO: a bunch of win32 calls for funny window properties I still haven't ported to other platforms.
// Make sure window thread doesn't keep hold of the GL context.
SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero);
if (OperatingSystem.IsWindows())
{
SDL_SysWMinfo info = default;
SDL_VERSION(out info.version);
if (SDL_GetWindowWMInfo(window, ref info) == SDL_TRUE && info.subsystem == SDL_SYSWM_WINDOWS)
WsiShared.WindowsSharedWindowCreate((HWND) info.info.win.window, _cfg);
}
if (parameters.Visible)
SDL_ShowWindow(window);
return (window, glContext);
}
private unsafe Sdl2WindowReg WinThreadSetupWindow(nint window, nint context)
{
var reg = new Sdl2WindowReg
{
Sdl2Window = window,
GlContext = context,
WindowId = SDL_GetWindowID(window),
Id = new WindowId(_nextWindowId++)
};
var handle = new WindowHandle(_clyde, reg);
reg.Handle = handle;
SDL_VERSION(out reg.SysWMinfo.version);
var res = SDL_GetWindowWMInfo(window, ref reg.SysWMinfo);
if (res == SDL_FALSE)
_sawmill.Error("Failed to get window WM info: {error}", SDL_GetError());
// LoadWindowIcon(window);
SDL_GetWindowSizeInPixels(window, out var fbW, out var fbH);
reg.FramebufferSize = (fbW, fbH);
reg.WindowScale = GetWindowScale(window);
SDL_GetWindowSize(window, out var w, out var h);
reg.PrevWindowSize = reg.WindowSize = (w, h);
SDL_GetWindowPosition(window, out var x, out var y);
reg.PrevWindowPos = (x, y);
reg.PixelRatio = reg.FramebufferSize / (Vector2) reg.WindowSize;
return reg;
}
public void WindowDestroy(WindowReg window)
{
var reg = (Sdl2WindowReg) window;
SendCmd(new CmdWinDestroy(reg.Sdl2Window, window.Owner != null));
}
public void UpdateMainWindowMode()
{
if (_clyde._mainWindow == null)
return;
var win = (Sdl2WindowReg) _clyde._mainWindow;
SendCmd(new CmdWinWinSetMode(win.Sdl2Window, _clyde._windowMode));
}
private static void WinThreadWinSetMode(CmdWinWinSetMode cmd)
{
var flags = cmd.Mode switch
{
WindowMode.Fullscreen => (uint) SDL_WINDOW_FULLSCREEN_DESKTOP,
_ => 0u
};
SDL_SetWindowFullscreen(cmd.Window, flags);
}
public void WindowSetTitle(WindowReg window, string title)
{
SendCmd(new CmdWinSetTitle(WinPtr(window), title));
}
private static void WinThreadWinSetTitle(CmdWinSetTitle cmd)
{
SDL_SetWindowTitle(cmd.Window, cmd.Title);
}
public void WindowSetMonitor(WindowReg window, IClydeMonitor monitor)
{
// API isn't really used and kinda wack, don't feel like figuring it out for SDL2 yet.
_sawmill.Warning("WindowSetMonitor not implemented on SDL2");
}
public void WindowSetSize(WindowReg window, Vector2i size)
{
SendCmd(new CmdWinSetSize(WinPtr(window), size.X, size.Y));
}
public void WindowSetVisible(WindowReg window, bool visible)
{
window.IsVisible = visible;
SendCmd(new CmdWinSetVisible(WinPtr(window), visible));
}
private static void WinThreadWinSetSize(CmdWinSetSize cmd)
{
SDL_SetWindowSize(cmd.Window, cmd.W, cmd.H);
}
private static void WinThreadWinSetVisible(CmdWinSetVisible cmd)
{
if (cmd.Visible)
SDL_ShowWindow(cmd.Window);
else
SDL_HideWindow(cmd.Window);
}
public void WindowRequestAttention(WindowReg window)
{
SendCmd(new CmdWinRequestAttention(WinPtr(window)));
}
private void WinThreadWinRequestAttention(CmdWinRequestAttention cmd)
{
var res = SDL_FlashWindow(cmd.Window, SDL_FLASH_UNTIL_FOCUSED);
if (res < 0)
_sawmill.Error("Failed to flash window: {error}", SDL_GetError());
}
public unsafe void WindowSwapBuffers(WindowReg window)
{
var reg = (Sdl2WindowReg)window;
var windowPtr = WinPtr(reg);
// On Windows, SwapBuffers does not correctly sync to the DWM compositor.
// This means OpenGL vsync is effectively broken by default on Windows.
// We manually sync via DwmFlush(). GLFW does this automatically, SDL2 does not.
//
// Windows DwmFlush logic partly taken from:
// https://github.com/love2d/love/blob/5175b0d1b599ea4c7b929f6b4282dd379fa116b8/src/modules/window/sdl/Window.cpp#L1018
// https://github.com/glfw/glfw/blob/d3ede7b6847b66cf30b067214b2b4b126d4c729b/src/wgl_context.c#L321-L340
// See also: https://github.com/libsdl-org/SDL/issues/5797
var dwmFlush = false;
var swapInterval = 0;
if (OperatingSystem.IsWindows() && !reg.Fullscreen && reg.SwapInterval > 0)
{
BOOL compositing;
// 6.2 is Windows 8
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_osversioninfoexw
if (OperatingSystem.IsWindowsVersionAtLeast(6, 2)
|| Windows.SUCCEEDED(Windows.DwmIsCompositionEnabled(&compositing)) && compositing)
{
var curCtx = SDL_GL_GetCurrentContext();
var curWin = SDL_GL_GetCurrentWindow();
if (curCtx != reg.GlContext || curWin != reg.Sdl2Window)
throw new InvalidOperationException("Window context must be current!");
SDL_GL_SetSwapInterval(0);
dwmFlush = true;
swapInterval = reg.SwapInterval;
}
}
SDL_GL_SwapWindow(windowPtr);
if (dwmFlush)
{
var i = swapInterval;
while (i-- > 0)
{
Windows.DwmFlush();
}
SDL_GL_SetSwapInterval(swapInterval);
}
}
public uint? WindowGetX11Id(WindowReg window)
{
CheckWindowDisposed(window);
var reg = (Sdl2WindowReg) window;
if (reg.SysWMinfo.subsystem != SDL_SYSWM_X11)
return null;
return (uint?) reg.SysWMinfo.info.x11.window;
}
public nint? WindowGetX11Display(WindowReg window)
{
CheckWindowDisposed(window);
var reg = (Sdl2WindowReg) window;
if (reg.SysWMinfo.subsystem != SDL_SYSWM_X11)
return null;
return reg.SysWMinfo.info.x11.display;
}
public nint? WindowGetWin32Window(WindowReg window)
{
CheckWindowDisposed(window);
var reg = (Sdl2WindowReg) window;
if (reg.SysWMinfo.subsystem != SDL_SYSWM_WINDOWS)
return null;
return reg.SysWMinfo.info.win.window;
}
public void RunOnWindowThread(Action a)
{
SendCmd(new CmdRunAction(a));
}
public void TextInputSetRect(UIBox2i rect)
{
SendCmd(new CmdTextInputSetRect(new SDL_Rect
{
x = rect.Left,
y = rect.Top,
w = rect.Width,
h = rect.Height
}));
}
private static void WinThreadSetTextInputRect(CmdTextInputSetRect cmdTextInput)
{
var rect = cmdTextInput.Rect;
SDL_SetTextInputRect(ref rect);
}
public void TextInputStart()
{
SendCmd(CmdTextInputStart.Instance);
}
private static void WinThreadStartTextInput()
{
SDL_StartTextInput();
}
public void TextInputStop()
{
SendCmd(CmdTextInputStop.Instance);
}
private static void WinThreadStopTextInput()
{
SDL_StopTextInput();
}
public void ClipboardSetText(WindowReg mainWindow, string text)
{
SendCmd(new CmdSetClipboard(text));
}
private void WinThreadSetClipboard(CmdSetClipboard cmd)
{
var res = SDL_SetClipboardText(cmd.Text);
if (res < 0)
_sawmill.Error("Failed to set clipboard text: {error}", SDL_GetError());
}
public Task<string> ClipboardGetText(WindowReg mainWindow)
{
var tcs = new TaskCompletionSource<string>();
SendCmd(new CmdGetClipboard(tcs));
return tcs.Task;
}
private static void WinThreadGetClipboard(CmdGetClipboard cmd)
{
cmd.Tcs.TrySetResult(SDL_GetClipboardText());
}
private static Vector2 GetWindowScale(nint window)
{
// Get scale by diving size in pixels with size in points.
SDL_GetWindowSizeInPixels(window, out var pixW, out var pixH);
SDL_GetWindowSize(window, out var pointW, out var pointH);
// Avoiding degenerate cases, not sure if these can actually happen.
if (pixW == 0 || pixH == 0 || pointW == 0 || pointH == 0)
return new Vector2(1, 1);
var scaleH = pixW / (float) pointW;
var scaleV = pixH / (float) pointH;
// Round to 5% increments to avoid rounding errors causing constantly different scales.
scaleH = MathF.Round(scaleH * 20) / 20;
scaleV = MathF.Round(scaleV * 20) / 20;
return new Vector2(scaleH, scaleV);
}
private static void CheckWindowDisposed(WindowReg reg)
{
if (reg.IsDisposed)
throw new ObjectDisposedException("Window disposed");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static nint WinPtr(WindowReg reg) => ((Sdl2WindowReg)reg).Sdl2Window;
private WindowReg? FindWindow(uint windowId)
{
foreach (var windowReg in _clyde._windows)
{
var glfwReg = (Sdl2WindowReg) windowReg;
if (glfwReg.WindowId == windowId)
return windowReg;
}
return null;
}
private sealed class Sdl2WindowReg : WindowReg
{
public nint Sdl2Window;
public uint WindowId;
public nint GlContext;
public SDL_SysWMinfo SysWMinfo;
#pragma warning disable CS0649
public bool Fullscreen;
#pragma warning restore CS0649
public int SwapInterval;
// Kept around to avoid it being GCd.
public CursorImpl? Cursor;
}
}
}

View File

@@ -0,0 +1,190 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using static SDL2.SDL;
using static SDL2.SDL.SDL_LogCategory;
using DependencyAttribute = Robust.Shared.IoC.DependencyAttribute;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl2WindowingImpl : IWindowingImpl
{
[Dependency] private readonly ILogManager _logManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
private readonly Clyde _clyde;
private GCHandle _selfGCHandle;
private readonly ISawmill _sawmill;
private readonly ISawmill _sawmillSdl2;
public Sdl2WindowingImpl(Clyde clyde, IDependencyCollection deps)
{
_clyde = clyde;
deps.InjectDependencies(this, true);
_sawmill = _logManager.GetSawmill("clyde.win");
_sawmillSdl2 = _logManager.GetSawmill("clyde.win.sdl2");
}
public bool Init()
{
InitChannels();
if (!InitSdl2())
return false;
return true;
}
private unsafe bool InitSdl2()
{
_selfGCHandle = GCHandle.Alloc(this, GCHandleType.Normal);
SDL_LogSetAllPriority(SDL_LogPriority.SDL_LOG_PRIORITY_VERBOSE);
SDL_LogSetOutputFunction(&LogOutputFunction, (void*) GCHandle.ToIntPtr(_selfGCHandle));
SDL_SetHint("SDL_WINDOWS_DPI_SCALING", "1");
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
SDL_SetHint(SDL_HINT_IME_SUPPORT_EXTENDED_TEXT, "1");
SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
var res = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
if (res < 0)
{
_sawmill.Fatal("Failed to initialize SDL2: {error}", SDL_GetError());
return false;
}
SDL_GetVersion(out var version);
var videoDriver = SDL_GetCurrentVideoDriver();
_sawmill.Debug(
"SDL2 initialized, version: {major}.{minor}.{patch}, video driver: {videoDriver}", version.major, version.minor, version.patch, videoDriver);
_sdlEventWakeup = SDL_RegisterEvents(1);
SDL_EventState(SDL_EventType.SDL_SYSWMEVENT, SDL_ENABLE);
InitCursors();
InitMonitors();
ReloadKeyMap();
SDL_AddEventWatch(&EventWatch, (void*) GCHandle.ToIntPtr(_selfGCHandle));
// SDL defaults to having text input enabled, so we have to manually turn it off in init for consistency.
// If we don't, text input will remain enabled *until* the user first leaves a LineEdit/TextEdit.
SDL_StopTextInput();
return true;
}
public unsafe void Shutdown()
{
if (_selfGCHandle != default)
{
SDL_DelEventWatch(&EventWatch, (void*) GCHandle.ToIntPtr(_selfGCHandle));
_selfGCHandle.Free();
}
SDL_LogSetOutputFunction(null, null);
if (SDL_WasInit(0) != 0)
{
_sawmill.Debug("Terminating SDL2");
SDL_Quit();
}
}
public void FlushDispose()
{
// Not currently used
}
public void GLMakeContextCurrent(WindowReg? reg)
{
int res;
if (reg is Sdl2WindowReg sdlReg)
res = SDL_GL_MakeCurrent(sdlReg.Sdl2Window, sdlReg.GlContext);
else
res = SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero);
if (res < 0)
_sawmill.Error("SDL_GL_MakeCurrent failed: {error}", SDL_GetError());
}
public void GLSwapInterval(WindowReg reg, int interval)
{
((Sdl2WindowReg)reg).SwapInterval = interval;
SDL_GL_SetSwapInterval(interval);
}
public unsafe void* GLGetProcAddress(string procName)
{
return (void*) SDL_GL_GetProcAddress(procName);
}
public string GetDescription()
{
SDL_GetVersion(out var version);
_sawmill.Debug(
"SDL2 initialized, version: {major}.{minor}.{patch}", version.major, version.minor, version.patch);
var videoDriver = SDL_GetCurrentVideoDriver();
return $"SDL2 {version.major}.{version.minor}.{version.patch} ({videoDriver})";
}
[UnmanagedCallersOnly(CallConvs = new []{typeof(CallConvCdecl)})]
private static unsafe void LogOutputFunction(
void* userdata,
int category,
SDL_LogPriority priority,
byte* message)
{
var obj = (Sdl2WindowingImpl) GCHandle.FromIntPtr((IntPtr)userdata).Target!;
var level = priority switch
{
SDL_LogPriority.SDL_LOG_PRIORITY_VERBOSE => LogLevel.Verbose,
SDL_LogPriority.SDL_LOG_PRIORITY_DEBUG => LogLevel.Debug,
SDL_LogPriority.SDL_LOG_PRIORITY_INFO => LogLevel.Info,
SDL_LogPriority.SDL_LOG_PRIORITY_WARN => LogLevel.Warning,
SDL_LogPriority.SDL_LOG_PRIORITY_ERROR => LogLevel.Error,
SDL_LogPriority.SDL_LOG_PRIORITY_CRITICAL => LogLevel.Fatal,
_ => LogLevel.Error
};
var msg = Marshal.PtrToStringUTF8((IntPtr) message) ?? "";
if (msg == "That operation is not supported")
{
obj._sawmillSdl2.Info(Environment.StackTrace);
}
var categoryName = SdlLogCategoryName(category);
obj._sawmillSdl2.Log(level, $"[{categoryName}] {msg}");
}
private static string SdlLogCategoryName(int category)
{
return (SDL_LogCategory) category switch {
// @formatter:off
SDL_LOG_CATEGORY_APPLICATION => "application",
SDL_LOG_CATEGORY_ERROR => "error",
SDL_LOG_CATEGORY_ASSERT => "assert",
SDL_LOG_CATEGORY_SYSTEM => "system",
SDL_LOG_CATEGORY_AUDIO => "audio",
SDL_LOG_CATEGORY_VIDEO => "video",
SDL_LOG_CATEGORY_RENDER => "render",
SDL_LOG_CATEGORY_INPUT => "input",
SDL_LOG_CATEGORY_TEST => "test",
_ => "unknown"
// @formatter:on
};
}
}
}

View File

@@ -1,145 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Robust.Client.UserInterface;
using SDL3;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl : IFileDialogManager
{
public async Task<Stream?> OpenFile(FileDialogFilters? filters = null)
{
var fileName = await ShowFileDialogOfType(SDL.SDL_FILEDIALOG_OPENFILE, filters);
if (fileName == null)
return null;
return File.OpenRead(fileName);
}
public async Task<(Stream fileStream, bool alreadyExisted)?> SaveFile(FileDialogFilters? filters = null, bool truncate = true)
{
var fileName = await ShowFileDialogOfType(SDL.SDL_FILEDIALOG_SAVEFILE, filters);
if (fileName == null)
return null;
try
{
return (File.Open(fileName, truncate ? FileMode.Truncate : FileMode.Open), true);
}
catch (FileNotFoundException)
{
return (File.Open(fileName, FileMode.Create), false);
}
}
private unsafe Task<string?> ShowFileDialogOfType(int type, FileDialogFilters? filters)
{
var props = SDL.SDL_CreateProperties();
SDL.SDL_DialogFileFilter* filtersAlloc = null;
if (filters != null)
{
filtersAlloc = (SDL.SDL_DialogFileFilter*)NativeMemory.Alloc(
(UIntPtr)filters.Groups.Count,
(UIntPtr)sizeof(SDL.SDL_DialogFileFilter));
SDL.SDL_SetNumberProperty(props, SDL.SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER, filters.Groups.Count);
SDL.SDL_SetPointerProperty(props, SDL.SDL_PROP_FILE_DIALOG_FILTERS_POINTER, (nint)filtersAlloc);
// All these mallocs aren't gonna win any performance awards, but oh well.
for (var i = 0; i < filters.Groups.Count; i++)
{
var (name, pattern) = ConvertFilterGroup(filters.Groups[i]);
filtersAlloc[i].name = StringToNative(name);
filtersAlloc[i].pattern = StringToNative(pattern);
}
}
var task = ShowFileDialogWithProperties(type, props);
SDL.SDL_DestroyProperties(props);
if (filtersAlloc != null)
{
for (var i = 0; i < filters!.Groups.Count; i++)
{
var filter = filtersAlloc[i];
NativeMemory.Free(filter.name);
NativeMemory.Free(filter.pattern);
}
}
return task;
}
private static unsafe byte* StringToNative(string str)
{
var byteCount = Encoding.UTF8.GetByteCount(str);
var mem = (byte*) NativeMemory.Alloc((nuint)(byteCount + 1));
Encoding.UTF8.GetBytes(str, new Span<byte>(mem, byteCount));
mem[byteCount] = 0; // null-terminate
return mem;
}
private (string name, string pattern) ConvertFilterGroup(FileDialogFilters.Group group)
{
var name = string.Join(", ", group.Extensions.Select(e => $"*.{e}"));
var pattern = string.Join(";", group.Extensions);
return (name, pattern);
}
private unsafe Task<string?> ShowFileDialogWithProperties(int type, uint properties)
{
var tcs = new TaskCompletionSource<string?>();
var gcHandle = GCHandle.Alloc(new FileDialogState
{
Parent = this,
Tcs = tcs
});
SDL.SDL_ShowFileDialogWithProperties(
type,
&FileDialogCallback,
(void*)GCHandle.ToIntPtr(gcHandle),
properties);
return tcs.Task;
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static unsafe void FileDialogCallback(void* userdata, byte** filelist, int filter)
{
var stateHandle = GCHandle.FromIntPtr((IntPtr)userdata);
var state = (FileDialogState)stateHandle.Target!;
stateHandle.Free();
if (filelist == null)
{
// Error
state.Parent._sawmill.Error("File dialog failed: {error}", SDL.SDL_GetError());
state.Tcs.SetResult(null);
return;
}
// Handles null (cancelled/none selected) transparently.
var str = Marshal.PtrToStringUTF8((nint) filelist[0]);
state.Tcs.SetResult(str);
}
private sealed class FileDialogState
{
public required Sdl3WindowingImpl Parent;
public required TaskCompletionSource<string?> Tcs;
}
}
}

View File

@@ -1,225 +0,0 @@
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using SDL3;
using Key = Robust.Client.Input.Keyboard.Key;
using Button = Robust.Client.Input.Mouse.Button;
using SC = SDL3.SDL.SDL_Scancode;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
{
// Indices are values of SDL_Scancode
private static readonly Key[] KeyMap;
private static readonly FrozenDictionary<Key, SC> KeyMapReverse;
private static readonly Button[] MouseButtonMap;
// TODO: to avoid having to ask the windowing thread, key names are cached.
private readonly Dictionary<Key, string> _printableKeyNameMap = new();
private void ReloadKeyMap()
{
// This may be ran concurrently from the windowing thread.
lock (_printableKeyNameMap)
{
_printableKeyNameMap.Clear();
// TODO: Validate this is correct in SDL3.
// List of mappable keys from SDL2's source appears to be:
// entries in SDL_default_keymap that aren't an SDLK_ enum reference.
// (the actual logic is more nuanced, but it appears to match the above)
// Comes out to these two ranges:
for (var k = SC.SDL_SCANCODE_A; k <= SC.SDL_SCANCODE_0; k++)
{
CacheKey(k);
}
for (var k = SC.SDL_SCANCODE_MINUS; k <= SC.SDL_SCANCODE_SLASH; k++)
{
CacheKey(k);
}
void CacheKey(SC scancode)
{
var rKey = ConvertSdl3Scancode(scancode);
if (rKey == Key.Unknown)
return;
// TODO: SDL_GetKeyFromScancode correct?
var name = SDL.SDL_GetKeyName(
SDL.SDL_GetKeyFromScancode(scancode, SDL.SDL_Keymod.SDL_KMOD_NONE, false));
if (!string.IsNullOrEmpty(name))
_printableKeyNameMap.Add(rKey, name);
}
}
}
public string? KeyGetName(Key key)
{
lock (_printableKeyNameMap)
{
if (_printableKeyNameMap.TryGetValue(key, out var name))
return name;
return null;
}
}
internal static Key ConvertSdl3Scancode(SC scancode)
{
return KeyMap[(int) scancode];
}
public static Button ConvertSdl3Button(int button)
{
return MouseButtonMap[button];
}
static Sdl3WindowingImpl()
{
MouseButtonMap = new Button[6];
MouseButtonMap[SDL.SDL_BUTTON_LEFT] = Button.Left;
MouseButtonMap[SDL.SDL_BUTTON_RIGHT] = Button.Right;
MouseButtonMap[SDL.SDL_BUTTON_MIDDLE] = Button.Middle;
MouseButtonMap[SDL.SDL_BUTTON_X1] = Button.Button4;
MouseButtonMap[SDL.SDL_BUTTON_X2] = Button.Button5;
KeyMap = new Key[(int) SC.SDL_SCANCODE_COUNT];
MapKey(SC.SDL_SCANCODE_A, Key.A);
MapKey(SC.SDL_SCANCODE_B, Key.B);
MapKey(SC.SDL_SCANCODE_C, Key.C);
MapKey(SC.SDL_SCANCODE_D, Key.D);
MapKey(SC.SDL_SCANCODE_E, Key.E);
MapKey(SC.SDL_SCANCODE_F, Key.F);
MapKey(SC.SDL_SCANCODE_G, Key.G);
MapKey(SC.SDL_SCANCODE_H, Key.H);
MapKey(SC.SDL_SCANCODE_I, Key.I);
MapKey(SC.SDL_SCANCODE_J, Key.J);
MapKey(SC.SDL_SCANCODE_K, Key.K);
MapKey(SC.SDL_SCANCODE_L, Key.L);
MapKey(SC.SDL_SCANCODE_M, Key.M);
MapKey(SC.SDL_SCANCODE_N, Key.N);
MapKey(SC.SDL_SCANCODE_O, Key.O);
MapKey(SC.SDL_SCANCODE_P, Key.P);
MapKey(SC.SDL_SCANCODE_Q, Key.Q);
MapKey(SC.SDL_SCANCODE_R, Key.R);
MapKey(SC.SDL_SCANCODE_S, Key.S);
MapKey(SC.SDL_SCANCODE_T, Key.T);
MapKey(SC.SDL_SCANCODE_U, Key.U);
MapKey(SC.SDL_SCANCODE_V, Key.V);
MapKey(SC.SDL_SCANCODE_W, Key.W);
MapKey(SC.SDL_SCANCODE_X, Key.X);
MapKey(SC.SDL_SCANCODE_Y, Key.Y);
MapKey(SC.SDL_SCANCODE_Z, Key.Z);
MapKey(SC.SDL_SCANCODE_0, Key.Num0);
MapKey(SC.SDL_SCANCODE_1, Key.Num1);
MapKey(SC.SDL_SCANCODE_2, Key.Num2);
MapKey(SC.SDL_SCANCODE_3, Key.Num3);
MapKey(SC.SDL_SCANCODE_4, Key.Num4);
MapKey(SC.SDL_SCANCODE_5, Key.Num5);
MapKey(SC.SDL_SCANCODE_6, Key.Num6);
MapKey(SC.SDL_SCANCODE_7, Key.Num7);
MapKey(SC.SDL_SCANCODE_8, Key.Num8);
MapKey(SC.SDL_SCANCODE_9, Key.Num9);
MapKey(SC.SDL_SCANCODE_KP_0, Key.NumpadNum0);
MapKey(SC.SDL_SCANCODE_KP_1, Key.NumpadNum1);
MapKey(SC.SDL_SCANCODE_KP_2, Key.NumpadNum2);
MapKey(SC.SDL_SCANCODE_KP_3, Key.NumpadNum3);
MapKey(SC.SDL_SCANCODE_KP_4, Key.NumpadNum4);
MapKey(SC.SDL_SCANCODE_KP_5, Key.NumpadNum5);
MapKey(SC.SDL_SCANCODE_KP_6, Key.NumpadNum6);
MapKey(SC.SDL_SCANCODE_KP_7, Key.NumpadNum7);
MapKey(SC.SDL_SCANCODE_KP_8, Key.NumpadNum8);
MapKey(SC.SDL_SCANCODE_KP_9, Key.NumpadNum9);
MapKey(SC.SDL_SCANCODE_ESCAPE, Key.Escape);
MapKey(SC.SDL_SCANCODE_LCTRL, Key.Control);
MapKey(SC.SDL_SCANCODE_RCTRL, Key.Control);
MapKey(SC.SDL_SCANCODE_RSHIFT, Key.Shift);
MapKey(SC.SDL_SCANCODE_LSHIFT, Key.Shift);
MapKey(SC.SDL_SCANCODE_LALT, Key.Alt);
MapKey(SC.SDL_SCANCODE_RALT, Key.Alt);
MapKey(SC.SDL_SCANCODE_LGUI, Key.LSystem);
MapKey(SC.SDL_SCANCODE_RGUI, Key.RSystem);
MapKey(SC.SDL_SCANCODE_MENU, Key.Menu);
MapKey(SC.SDL_SCANCODE_LEFTBRACKET, Key.LBracket);
MapKey(SC.SDL_SCANCODE_RIGHTBRACKET, Key.RBracket);
MapKey(SC.SDL_SCANCODE_SEMICOLON, Key.SemiColon);
MapKey(SC.SDL_SCANCODE_COMMA, Key.Comma);
MapKey(SC.SDL_SCANCODE_PERIOD, Key.Period);
MapKey(SC.SDL_SCANCODE_APOSTROPHE, Key.Apostrophe);
MapKey(SC.SDL_SCANCODE_SLASH, Key.Slash);
MapKey(SC.SDL_SCANCODE_BACKSLASH, Key.BackSlash);
MapKey(SC.SDL_SCANCODE_GRAVE, Key.Tilde);
MapKey(SC.SDL_SCANCODE_EQUALS, Key.Equal);
MapKey(SC.SDL_SCANCODE_SPACE, Key.Space);
MapKey(SC.SDL_SCANCODE_RETURN, Key.Return);
MapKey(SC.SDL_SCANCODE_KP_ENTER, Key.NumpadEnter);
MapKey(SC.SDL_SCANCODE_BACKSPACE, Key.BackSpace);
MapKey(SC.SDL_SCANCODE_TAB, Key.Tab);
MapKey(SC.SDL_SCANCODE_PAGEUP, Key.PageUp);
MapKey(SC.SDL_SCANCODE_PAGEDOWN, Key.PageDown);
MapKey(SC.SDL_SCANCODE_END, Key.End);
MapKey(SC.SDL_SCANCODE_HOME, Key.Home);
MapKey(SC.SDL_SCANCODE_INSERT, Key.Insert);
MapKey(SC.SDL_SCANCODE_DELETE, Key.Delete);
MapKey(SC.SDL_SCANCODE_MINUS, Key.Minus);
MapKey(SC.SDL_SCANCODE_KP_PLUS, Key.NumpadAdd);
MapKey(SC.SDL_SCANCODE_KP_MINUS, Key.NumpadSubtract);
MapKey(SC.SDL_SCANCODE_KP_DIVIDE, Key.NumpadDivide);
MapKey(SC.SDL_SCANCODE_KP_MULTIPLY, Key.NumpadMultiply);
MapKey(SC.SDL_SCANCODE_KP_DECIMAL, Key.NumpadDecimal);
MapKey(SC.SDL_SCANCODE_LEFT, Key.Left);
MapKey(SC.SDL_SCANCODE_RIGHT, Key.Right);
MapKey(SC.SDL_SCANCODE_UP, Key.Up);
MapKey(SC.SDL_SCANCODE_DOWN, Key.Down);
MapKey(SC.SDL_SCANCODE_F1, Key.F1);
MapKey(SC.SDL_SCANCODE_F2, Key.F2);
MapKey(SC.SDL_SCANCODE_F3, Key.F3);
MapKey(SC.SDL_SCANCODE_F4, Key.F4);
MapKey(SC.SDL_SCANCODE_F5, Key.F5);
MapKey(SC.SDL_SCANCODE_F6, Key.F6);
MapKey(SC.SDL_SCANCODE_F7, Key.F7);
MapKey(SC.SDL_SCANCODE_F8, Key.F8);
MapKey(SC.SDL_SCANCODE_F9, Key.F9);
MapKey(SC.SDL_SCANCODE_F10, Key.F10);
MapKey(SC.SDL_SCANCODE_F11, Key.F11);
MapKey(SC.SDL_SCANCODE_F12, Key.F12);
MapKey(SC.SDL_SCANCODE_F13, Key.F13);
MapKey(SC.SDL_SCANCODE_F14, Key.F14);
MapKey(SC.SDL_SCANCODE_F15, Key.F15);
MapKey(SC.SDL_SCANCODE_F16, Key.F16);
MapKey(SC.SDL_SCANCODE_F17, Key.F17);
MapKey(SC.SDL_SCANCODE_F18, Key.F18);
MapKey(SC.SDL_SCANCODE_F19, Key.F19);
MapKey(SC.SDL_SCANCODE_F20, Key.F20);
MapKey(SC.SDL_SCANCODE_F21, Key.F21);
MapKey(SC.SDL_SCANCODE_F22, Key.F22);
MapKey(SC.SDL_SCANCODE_F23, Key.F23);
MapKey(SC.SDL_SCANCODE_F24, Key.F24);
MapKey(SC.SDL_SCANCODE_PAUSE, Key.Pause);
var keyMapReverse = new Dictionary<Key, SC>();
for (var code = 0; code < KeyMap.Length; code++)
{
var key = KeyMap[code];
if (key != Key.Unknown)
keyMapReverse[key] = (SC) code;
}
KeyMapReverse = keyMapReverse.ToFrozenDictionary();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void MapKey(SC code, Key key)
{
KeyMap[(int)code] = key;
}
}
}
}

View File

@@ -1,133 +0,0 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using SDL3;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
{
// NOTE: SDL3 calls them "displays". GLFW calls them monitors. GLFW's is the one I'm going with.
private int _nextMonitorId = 1;
private readonly Dictionary<int, WinThreadMonitorReg> _winThreadMonitors = new();
private readonly Dictionary<int, Sdl3MonitorReg> _monitors = new();
private unsafe void InitMonitors()
{
var displayList = (uint*)SDL.SDL_GetDisplays(out var count);
for (var i = 0; i < count; i++)
{
WinThreadSetupMonitor(displayList[i]);
}
SDL.SDL_free((nint)displayList);
// Needed so that monitor creation events get processed.
ProcessEvents();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private unsafe void WinThreadSetupMonitor(uint displayId)
{
var id = _nextMonitorId++;
var name = SDL.SDL_GetDisplayName(displayId);
var modePtr = (SDL.SDL_DisplayMode**)SDL.SDL_GetFullscreenDisplayModes(displayId, out var modeCount);
var curMode = (SDL.SDL_DisplayMode*)SDL.SDL_GetCurrentDisplayMode(displayId);
var modes = new VideoMode[modeCount];
for (var i = 0; i < modes.Length; i++)
{
modes[i] = ConvertVideoMode(in *modePtr[i]);
}
SDL.SDL_free((nint)modePtr);
_winThreadMonitors.Add(id, new WinThreadMonitorReg { DisplayId = displayId });
if (SDL.SDL_GetPrimaryDisplay() == displayId)
_clyde._primaryMonitorId = id;
SendEvent(new EventMonitorSetup
{
Id = id,
DisplayId = displayId,
Name = name,
AllModes = modes,
CurrentMode = ConvertVideoMode(in *curMode),
});
}
private static VideoMode ConvertVideoMode(in SDL.SDL_DisplayMode mode)
{
return new()
{
Width = (ushort)mode.w,
Height = (ushort)mode.h,
RefreshRate = (ushort)mode.refresh_rate,
// TODO: set bits count based on format (I'm lazy)
RedBits = 8,
GreenBits = 8,
BlueBits = 8,
};
}
private void ProcessSetupMonitor(EventMonitorSetup ev)
{
var impl = new MonitorHandle(
ev.Id,
ev.Name,
(ev.CurrentMode.Width, ev.CurrentMode.Height),
ev.CurrentMode.RefreshRate,
ev.AllModes);
_clyde._monitorHandles.Add(ev.Id, impl);
_monitors[ev.Id] = new Sdl3MonitorReg
{
DisplayId = ev.DisplayId,
Handle = impl
};
}
private void WinThreadDestroyMonitor(uint displayId)
{
var monitorId = GetMonitorIdFromDisplayId(displayId);
if (monitorId == 0)
return;
_winThreadMonitors.Remove(monitorId);
SendEvent(new EventMonitorDestroy { Id = monitorId });
}
private void ProcessEventDestroyMonitor(EventMonitorDestroy ev)
{
_monitors.Remove(ev.Id);
_clyde._monitorHandles.Remove(ev.Id);
}
private int GetMonitorIdFromDisplayId(uint displayId)
{
foreach (var (id, monitorReg) in _winThreadMonitors)
{
if (monitorReg.DisplayId == displayId)
{
return id;
}
}
return 0;
}
private sealed class Sdl3MonitorReg : MonitorReg
{
public uint DisplayId;
}
private sealed class WinThreadMonitorReg
{
public uint DisplayId;
}
}
}

View File

@@ -1,282 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using SDL3;
using ET = SDL3.SDL.SDL_EventType;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
{
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static unsafe byte EventWatch(void* userdata, SDL.SDL_Event* sdlevent)
{
var obj = (Sdl3WindowingImpl)GCHandle.FromIntPtr((IntPtr)userdata).Target!;
obj.ProcessSdl3Event(in *sdlevent);
return 0;
}
private void ProcessSdl3Event(in SDL.SDL_Event ev)
{
switch ((ET)ev.type)
{
case ET.SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
ProcessSdl3EventWindowPixelSizeChanged(in ev.window);
break;
case ET.SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
ProcessSdl3EventWindowDisplayScaleChanged(in ev.window);
break;
case ET.SDL_EVENT_WINDOW_CLOSE_REQUESTED:
case ET.SDL_EVENT_WINDOW_MOUSE_ENTER:
case ET.SDL_EVENT_WINDOW_MOUSE_LEAVE:
case ET.SDL_EVENT_WINDOW_MINIMIZED:
case ET.SDL_EVENT_WINDOW_RESTORED:
case ET.SDL_EVENT_WINDOW_FOCUS_GAINED:
case ET.SDL_EVENT_WINDOW_FOCUS_LOST:
case ET.SDL_EVENT_WINDOW_MOVED:
ProcessSdl3EventWindowMisc(in ev.window);
break;
case ET.SDL_EVENT_KEY_DOWN:
case ET.SDL_EVENT_KEY_UP:
ProcessSdl3KeyEvent(in ev.key);
break;
case ET.SDL_EVENT_TEXT_INPUT:
ProcessSdl3EventTextInput(in ev.text);
break;
case ET.SDL_EVENT_TEXT_EDITING:
ProcessSdl3EventTextEditing(in ev.edit);
break;
case ET.SDL_EVENT_KEYMAP_CHANGED:
ProcessSdl3EventKeyMapChanged();
break;
case ET.SDL_EVENT_MOUSE_MOTION:
ProcessSdl3EventMouseMotion(in ev.motion);
break;
case ET.SDL_EVENT_MOUSE_BUTTON_DOWN:
case ET.SDL_EVENT_MOUSE_BUTTON_UP:
ProcessSdl3EventMouseButton(in ev.button);
break;
case ET.SDL_EVENT_MOUSE_WHEEL:
ProcessSdl3EventMouseWheel(in ev.wheel);
break;
case ET.SDL_EVENT_DISPLAY_ADDED:
WinThreadSetupMonitor(ev.display.displayID);
break;
case ET.SDL_EVENT_DISPLAY_REMOVED:
WinThreadDestroyMonitor(ev.display.displayID);
break;
case ET.SDL_EVENT_QUIT:
ProcessSdl3EventQuit();
break;
}
}
private void ProcessSdl3EventQuit()
{
SendEvent(new EventQuit());
}
private void ProcessSdl3EventMouseWheel(in SDL.SDL_MouseWheelEvent ev)
{
SendEvent(new EventWheel { WindowId = ev.windowID, XOffset = ev.x, YOffset = ev.y });
}
private void ProcessSdl3EventMouseButton(in SDL.SDL_MouseButtonEvent ev)
{
var mods = SDL.SDL_GetModState();
SendEvent(new EventMouseButton
{
WindowId = ev.windowID,
Type = ev.type,
Button = ev.button,
Mods = mods
});
}
private void ProcessSdl3EventMouseMotion(in SDL.SDL_MouseMotionEvent ev)
{
SendEvent(new EventMouseMotion
{
WindowId = ev.windowID,
X = ev.x,
Y = ev.y,
XRel = ev.xrel,
YRel = ev.yrel
});
}
private unsafe void ProcessSdl3EventTextInput(in SDL.SDL_TextInputEvent ev)
{
var str = Marshal.PtrToStringUTF8((IntPtr)ev.text) ?? "";
SendEvent(new EventText { WindowId = ev.windowID, Text = str });
}
private unsafe void ProcessSdl3EventTextEditing(in SDL.SDL_TextEditingEvent ev)
{
var str = Marshal.PtrToStringUTF8((IntPtr)ev.text) ?? "";
SendEvent(new EventTextEditing
{
WindowId = ev.windowID,
Text = str,
Start = ev.start,
Length = ev.length
});
}
private void ProcessSdl3EventKeyMapChanged()
{
ReloadKeyMap();
SendEvent(new EventKeyMapChanged());
}
private void ProcessSdl3KeyEvent(in SDL.SDL_KeyboardEvent ev)
{
SendEvent(new EventKey
{
WindowId = ev.windowID,
Scancode = ev.scancode,
Type = ev.type,
Repeat = ev.repeat,
Mods = ev.mod,
});
}
private void ProcessSdl3EventWindowPixelSizeChanged(in SDL.SDL_WindowEvent ev)
{
var window = SDL.SDL_GetWindowFromID(ev.windowID);
SDL.SDL_GetWindowSize(window, out var width, out var height);
var fbW = ev.data1;
var fbH = ev.data2;
SendEvent(new EventWindowPixelSize
{
WindowId = ev.windowID,
Width = width,
Height = height,
FramebufferWidth = fbW,
FramebufferHeight = fbH,
});
}
private void ProcessSdl3EventWindowDisplayScaleChanged(in SDL.SDL_WindowEvent ev)
{
var window = SDL.SDL_GetWindowFromID(ev.windowID);
var scale = SDL.SDL_GetWindowDisplayScale(window);
SendEvent(new EventWindowContentScale { WindowId = ev.windowID, Scale = scale });
}
private void ProcessSdl3EventWindowMisc(in SDL.SDL_WindowEvent ev)
{
SendEvent(new EventWindowMisc
{
WindowId = ev.windowID,
EventId = ev.type,
Data1 = ev.data1,
Data2 = ev.data2
});
}
private abstract class EventBase;
private sealed class EventWindowCreate : EventBase
{
public required Sdl3WindowCreateResult Result;
public required TaskCompletionSource<Sdl3WindowCreateResult> Tcs;
}
private sealed class EventKey : EventBase
{
public uint WindowId;
public SDL.SDL_Scancode Scancode;
public ET Type;
public bool Repeat;
public SDL.SDL_Keymod Mods;
}
private sealed class EventMouseMotion : EventBase
{
public uint WindowId;
public float X;
public float Y;
public float XRel;
public float YRel;
}
private sealed class EventMouseButton : EventBase
{
public uint WindowId;
public ET Type;
public byte Button;
public SDL.SDL_Keymod Mods;
}
private sealed class EventText : EventBase
{
public uint WindowId;
public required string Text;
}
private sealed class EventTextEditing : EventBase
{
public uint WindowId;
public required string Text;
public int Start;
public int Length;
}
private sealed class EventWindowPixelSize : EventBase
{
public uint WindowId;
public int Width;
public int Height;
public int FramebufferWidth;
public int FramebufferHeight;
}
private sealed class EventWindowContentScale : EventBase
{
public uint WindowId;
public float Scale;
}
private sealed class EventWheel : EventBase
{
public uint WindowId;
public float XOffset;
public float YOffset;
}
// SDL_WindowEvents that don't need any handling on the window thread itself.
private sealed class EventWindowMisc : EventBase
{
public uint WindowId;
public ET EventId;
public int Data1;
public int Data2;
}
private sealed class EventMonitorSetup : EventBase
{
public int Id;
public uint DisplayId;
public required string Name;
public VideoMode CurrentMode;
public required VideoMode[] AllModes;
}
private sealed class EventMonitorDestroy : EventBase
{
public int Id;
}
private sealed class EventKeyMapChanged : EventBase;
private sealed class EventQuit : EventBase;
}
}

View File

@@ -1,654 +0,0 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using SDL3;
using TerraFX.Interop.Windows;
using TerraFX.Interop.Xlib;
using BOOL = TerraFX.Interop.Windows.BOOL;
using Windows = TerraFX.Interop.Windows.Windows;
using GLAttr = SDL3.SDL.SDL_GLAttr;
using X11Window = TerraFX.Interop.Xlib.Window;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl
{
private int _nextWindowId = 1;
public (WindowReg?, string? error) WindowCreate(
GLContextSpec? spec,
WindowCreateParameters parameters,
WindowReg? share,
WindowReg? owner)
{
nint shareWindow = 0;
nint shareContext = 0;
if (share is Sdl3WindowReg shareReg)
{
shareWindow = shareReg.Sdl3Window;
shareContext = shareReg.GlContext;
}
nint ownerPtr = 0;
if (owner is Sdl3WindowReg ownerReg)
ownerPtr = ownerReg.Sdl3Window;
var task = SharedWindowCreate(spec, parameters, shareWindow, shareContext, ownerPtr);
// Block the main thread (to avoid stuff like texture uploads being problematic).
WaitWindowCreate(task);
#pragma warning disable RA0004
// Block above ensured task is done, this is safe.
var result = task.Result;
#pragma warning restore RA0004
if (result.Reg != null)
{
result.Reg.Owner = result.Reg.Handle;
}
return (result.Reg, result.Error);
}
private void WaitWindowCreate(Task<Sdl3WindowCreateResult> windowTask)
{
while (!windowTask.IsCompleted)
{
// Keep processing events until the window task gives either an error or success.
WaitEvents();
ProcessEvents(single: true);
}
}
private Task<Sdl3WindowCreateResult> SharedWindowCreate(
GLContextSpec? glSpec,
WindowCreateParameters parameters,
nint shareWindow,
nint shareContext,
nint owner)
{
//
// IF YOU'RE WONDERING WHY THIS IS TASK-BASED:
// I originally wanted this to be async so we could avoid blocking the main thread
// while the OS takes its stupid 100~ms just to initialize a fucking GL context.
// This doesn't *work* because
// we have to release the GL context while the shared context is being created.
// (at least on WGL, I didn't test other platforms and I don't care to.)
// Not worth it to avoid a main thread blockage by allowing Clyde to temporarily release the GL context,
// because rendering would be locked up *anyways*.
//
// Basically what I'm saying is that everything about OpenGL is a fucking mistake
// and I should get on either Veldrid or Vulkan some time.
// Probably Veldrid tbh.
//
// Yes we ping-pong this TCS through the window thread and back, deal with it.
var tcs = new TaskCompletionSource<Sdl3WindowCreateResult>();
SendCmd(new CmdWinCreate
{
GLSpec = glSpec,
Parameters = parameters,
ShareWindow = shareWindow,
ShareContext = shareContext,
OwnerWindow = owner,
Tcs = tcs
});
return tcs.Task;
}
private static void FinishWindowCreate(EventWindowCreate ev)
{
ev.Tcs.TrySetResult(ev.Result);
}
private void WinThreadWinCreate(CmdWinCreate cmd)
{
var (window, context) = CreateSdl3WindowForRenderer(
cmd.GLSpec,
cmd.Parameters,
cmd.ShareWindow,
cmd.ShareContext,
cmd.OwnerWindow);
if (window == 0)
{
var err = SDL.SDL_GetError();
SendEvent(new EventWindowCreate
{
Result = new Sdl3WindowCreateResult { Error = err },
Tcs = cmd.Tcs
});
return;
}
// We can't invoke the TCS directly from the windowing thread because:
// * it'd hit the synchronization context,
// which would make (blocking) main window init more annoying.
// * it'd not be synchronized to other incoming window events correctly which might be icky.
// So we send the TCS back to the game thread
// which processes events in the correct order and has better control of stuff during init.
var reg = WinThreadSetupWindow(window, context);
SendEvent(new EventWindowCreate
{
Result = new Sdl3WindowCreateResult { Reg = reg },
Tcs = cmd.Tcs
});
}
private static void WinThreadWinDestroy(CmdWinDestroy cmd)
{
SDL.SDL_DestroyWindow(cmd.Window);
}
private (nint window, nint context) CreateSdl3WindowForRenderer(
GLContextSpec? spec,
WindowCreateParameters parameters,
nint shareWindow,
nint shareContext,
nint ownerWindow)
{
var createProps = SDL.SDL_CreateProperties();
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, true);
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true);
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
if (spec is { } s)
{
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_RED_SIZE, 8);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_GREEN_SIZE, 8);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_BLUE_SIZE, 8);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_ALPHA_SIZE, 8);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_STENCIL_SIZE, 8);
SDL.SDL_GL_SetAttribute(
GLAttr.SDL_GL_FRAMEBUFFER_SRGB_CAPABLE,
s.Profile == GLContextProfile.Es ? 0 : 1);
int ctxFlags = 0;
#if DEBUG
ctxFlags |= SDL.SDL_GL_CONTEXT_DEBUG_FLAG;
#endif
if (s.Profile == GLContextProfile.Core)
ctxFlags |= SDL.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_CONTEXT_FLAGS, (int)ctxFlags);
if (shareContext != 0)
{
SDL.SDL_GL_MakeCurrent(shareWindow, shareContext);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
}
else
{
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
}
var profile = s.Profile switch
{
GLContextProfile.Compatibility => SDL.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY,
GLContextProfile.Core => SDL.SDL_GL_CONTEXT_PROFILE_CORE,
GLContextProfile.Es => SDL.SDL_GL_CONTEXT_PROFILE_ES,
_ => SDL.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY,
};
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_CONTEXT_PROFILE_MASK, profile);
SDL.SDL_SetHint(SDL.SDL_HINT_OPENGL_ES_DRIVER, s.CreationApi == GLContextCreationApi.Egl ? "1" : "0");
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_CONTEXT_MAJOR_VERSION, s.Major);
SDL.SDL_GL_SetAttribute(GLAttr.SDL_GL_CONTEXT_MINOR_VERSION, s.Minor);
if (s.CreationApi == GLContextCreationApi.Egl)
WsiShared.EnsureEglAvailable();
}
if (parameters.Fullscreen)
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN, true);
if ((parameters.Styles & OSWindowStyles.NoTitleBar) != 0)
SDL.SDL_SetBooleanProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN, true);
if (ownerWindow != 0)
{
SDL.SDL_SetPointerProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_PARENT_POINTER, ownerWindow);
if (parameters.StartupLocation == WindowStartupLocation.CenterOwner)
{
SDL.SDL_GetWindowSize(ownerWindow, out var parentW, out var parentH);
SDL.SDL_GetWindowPosition(ownerWindow, out var parentX, out var parentY);
SDL.SDL_SetNumberProperty(
createProps,
SDL.SDL_PROP_WINDOW_CREATE_X_NUMBER,
parentX + (parentW - parameters.Width) / 2);
SDL.SDL_SetNumberProperty(
createProps,
SDL.SDL_PROP_WINDOW_CREATE_Y_NUMBER,
parentY + (parentH - parameters.Height) / 2);
}
}
SDL.SDL_SetNumberProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, parameters.Width);
SDL.SDL_SetNumberProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, parameters.Height);
SDL.SDL_SetStringProperty(createProps, SDL.SDL_PROP_WINDOW_CREATE_TITLE_STRING, parameters.Title);
// ---> CREATE <---
var window = SDL.SDL_CreateWindowWithProperties(createProps);
SDL.SDL_DestroyProperties(createProps);
if (window == 0)
return default;
nint glContext = SDL.SDL_GL_CreateContext(window);
if (glContext == 0)
{
SDL.SDL_DestroyWindow(window);
return default;
}
if ((parameters.Styles & OSWindowStyles.NoTitleOptions) != 0)
{
var props = SDL.SDL_GetWindowProperties(window);
switch (_videoDriver)
{
case SdlVideoDriver.Windows:
{
var hWnd = SDL.SDL_GetPointerProperty(
props,
SDL.SDL_PROP_WINDOW_WIN32_HWND_POINTER,
0);
WsiShared.SetWindowStyleNoTitleOptionsWindows((HWND)hWnd);
break;
}
case SdlVideoDriver.X11:
unsafe
{
var x11Display = (Display*)SDL.SDL_GetPointerProperty(
props,
SDL.SDL_PROP_WINDOW_X11_DISPLAY_POINTER,
0);
var x11Window = (X11Window)SDL.SDL_GetNumberProperty(
props,
SDL.SDL_PROP_WINDOW_X11_WINDOW_NUMBER,
0);
WsiShared.SetWindowStyleNoTitleOptionsX11(x11Display, x11Window);
break;
}
default:
_sawmill.Warning("OSWindowStyles.NoTitleOptions not implemented on this video driver");
break;
}
}
// TODO: Monitors, window maximize.
// Make sure window thread doesn't keep hold of the GL context.
SDL.SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero);
if (parameters.Visible)
SDL.SDL_ShowWindow(window);
return (window, glContext);
}
private Sdl3WindowReg WinThreadSetupWindow(nint window, nint context)
{
var reg = new Sdl3WindowReg
{
Sdl3Window = window,
GlContext = context,
WindowId = SDL.SDL_GetWindowID(window),
Id = new WindowId(_nextWindowId++)
};
var handle = new WindowHandle(_clyde, reg);
reg.Handle = handle;
var windowProps = SDL.SDL_GetWindowProperties(window);
switch (_videoDriver)
{
case SdlVideoDriver.Windows:
reg.WindowsHwnd = SDL.SDL_GetPointerProperty(
windowProps,
SDL.SDL_PROP_WINDOW_WIN32_HWND_POINTER,
0);
break;
case SdlVideoDriver.X11:
reg.X11Display = SDL.SDL_GetPointerProperty(
windowProps,
SDL.SDL_PROP_WINDOW_X11_DISPLAY_POINTER,
0);
reg.X11Id = (uint)SDL.SDL_GetNumberProperty(windowProps, SDL.SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0);
break;
}
AssignWindowIconToWindow(window);
SDL.SDL_GetWindowSizeInPixels(window, out var fbW, out var fbH);
reg.FramebufferSize = (fbW, fbH);
var scale = SDL.SDL_GetWindowDisplayScale(window);
reg.WindowScale = new Vector2(scale, scale);
SDL.SDL_GetWindowSize(window, out var w, out var h);
reg.PrevWindowSize = reg.WindowSize = (w, h);
SDL.SDL_GetWindowPosition(window, out var x, out var y);
reg.PrevWindowPos = reg.WindowPos = (x, y);
reg.PixelRatio = reg.FramebufferSize / (Vector2)reg.WindowSize;
return reg;
}
public void WindowDestroy(WindowReg window)
{
var reg = (Sdl3WindowReg)window;
SendCmd(new CmdWinDestroy
{
Window = reg.Sdl3Window,
HadOwner = window.Owner != null
});
}
public void UpdateMainWindowMode()
{
if (_clyde._mainWindow == null)
return;
var win = (Sdl3WindowReg)_clyde._mainWindow;
if (_clyde._windowMode == WindowMode.Fullscreen)
{
win.PrevWindowSize = win.WindowSize;
win.PrevWindowPos = win.WindowPos;
SendCmd(new CmdWinWinSetFullscreen
{
Window = win.Sdl3Window,
});
}
else
{
SendCmd(new CmdWinSetWindowed
{
Window = win.Sdl3Window,
Width = win.PrevWindowSize.X,
Height = win.PrevWindowSize.Y,
PosX = win.PrevWindowPos.X,
PosY = win.PrevWindowPos.Y
});
}
}
private static void WinThreadWinSetFullscreen(CmdWinWinSetFullscreen cmd)
{
SDL.SDL_SetWindowFullscreen(cmd.Window, true);
}
private static void WinThreadWinSetWindowed(CmdWinSetWindowed cmd)
{
SDL.SDL_SetWindowFullscreen(cmd.Window, false);
SDL.SDL_SetWindowSize(cmd.Window, cmd.Width, cmd.Height);
SDL.SDL_SetWindowPosition(cmd.Window, cmd.PosX, cmd.PosY);
}
public void WindowSetTitle(WindowReg window, string title)
{
SendCmd(new CmdWinSetTitle
{
Window = WinPtr(window),
Title = title,
});
}
private static void WinThreadWinSetTitle(CmdWinSetTitle cmd)
{
SDL.SDL_SetWindowTitle(cmd.Window, cmd.Title);
}
public void WindowSetMonitor(WindowReg window, IClydeMonitor monitor)
{
// API isn't really used and kinda wack, don't feel like figuring it out for SDL3 yet.
_sawmill.Warning("WindowSetMonitor not implemented on SDL3");
}
public void WindowSetSize(WindowReg window, Vector2i size)
{
SendCmd(new CmdWinSetSize { Window = WinPtr(window), W = size.X, H = size.Y });
}
public void WindowSetVisible(WindowReg window, bool visible)
{
window.IsVisible = visible;
SendCmd(new CmdWinSetVisible { Window = WinPtr(window), Visible = visible });
}
private static void WinThreadWinSetSize(CmdWinSetSize cmd)
{
SDL.SDL_SetWindowSize(cmd.Window, cmd.W, cmd.H);
}
private static void WinThreadWinSetVisible(CmdWinSetVisible cmd)
{
if (cmd.Visible)
SDL.SDL_ShowWindow(cmd.Window);
else
SDL.SDL_HideWindow(cmd.Window);
}
public void WindowRequestAttention(WindowReg window)
{
SendCmd(new CmdWinRequestAttention { Window = WinPtr(window) });
}
private void WinThreadWinRequestAttention(CmdWinRequestAttention cmd)
{
var res = SDL.SDL_FlashWindow(cmd.Window, SDL.SDL_FlashOperation.SDL_FLASH_UNTIL_FOCUSED);
if (!res)
_sawmill.Error("Failed to flash window: {error}", SDL.SDL_GetError());
}
public unsafe void WindowSwapBuffers(WindowReg window)
{
var reg = (Sdl3WindowReg)window;
var windowPtr = WinPtr(reg);
// On Windows, SwapBuffers does not correctly sync to the DWM compositor.
// This means OpenGL vsync is effectively broken by default on Windows.
// We manually sync via DwmFlush(). GLFW does this automatically, SDL3 does not.
//
// Windows DwmFlush logic partly taken from:
// https://github.com/love2d/love/blob/5175b0d1b599ea4c7b929f6b4282dd379fa116b8/src/modules/window/sdl/Window.cpp#L1018
// https://github.com/glfw/glfw/blob/d3ede7b6847b66cf30b067214b2b4b126d4c729b/src/wgl_context.c#L321-L340
// See also: https://github.com/libsdl-org/SDL/issues/5797
var dwmFlush = false;
var swapInterval = 0;
if (OperatingSystem.IsWindows() && !reg.Fullscreen && reg.SwapInterval > 0)
{
BOOL compositing;
// 6.2 is Windows 8
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_osversioninfoexw
if (OperatingSystem.IsWindowsVersionAtLeast(6, 2)
|| Windows.SUCCEEDED(Windows.DwmIsCompositionEnabled(&compositing)) && compositing)
{
var curCtx = SDL.SDL_GL_GetCurrentContext();
var curWin = SDL.SDL_GL_GetCurrentWindow();
if (curCtx != reg.GlContext || curWin != reg.Sdl3Window)
throw new InvalidOperationException("Window context must be current!");
SDL.SDL_GL_SetSwapInterval(0);
dwmFlush = true;
swapInterval = reg.SwapInterval;
}
}
SDL.SDL_GL_SwapWindow(windowPtr);
if (dwmFlush)
{
var i = swapInterval;
while (i-- > 0)
{
Windows.DwmFlush();
}
SDL.SDL_GL_SetSwapInterval(swapInterval);
}
}
public uint? WindowGetX11Id(WindowReg window)
{
CheckWindowDisposed(window);
if (_videoDriver != SdlVideoDriver.X11)
return null;
var reg = (Sdl3WindowReg)window;
return reg.X11Id;
}
public nint? WindowGetX11Display(WindowReg window)
{
CheckWindowDisposed(window);
if (_videoDriver != SdlVideoDriver.X11)
return null;
var reg = (Sdl3WindowReg)window;
return reg.X11Display;
}
public nint? WindowGetWin32Window(WindowReg window)
{
CheckWindowDisposed(window);
if (_videoDriver != SdlVideoDriver.Windows)
return null;
var reg = (Sdl3WindowReg)window;
return reg.WindowsHwnd;
}
public void RunOnWindowThread(Action a)
{
SendCmd(new CmdRunAction { Action = a });
}
public void TextInputSetRect(WindowReg reg, UIBox2i rect, int cursor)
{
SendCmd(new CmdTextInputSetRect
{
Window = WinPtr(reg),
Rect = new SDL.SDL_Rect
{
x = rect.Left,
y = rect.Top,
w = rect.Width,
h = rect.Height
},
Cursor = cursor
});
}
private static void WinThreadSetTextInputRect(CmdTextInputSetRect cmdTextInput)
{
var rect = cmdTextInput.Rect;
SDL.SDL_SetTextInputArea(cmdTextInput.Window, ref rect, cmdTextInput.Cursor);
}
public void TextInputStart(WindowReg reg)
{
SendCmd(new CmdTextInputStart { Window = WinPtr(reg) });
}
private static void WinThreadStartTextInput(CmdTextInputStart cmd)
{
SDL.SDL_StartTextInput(cmd.Window);
}
public void TextInputStop(WindowReg reg)
{
SendCmd(new CmdTextInputStop { Window = WinPtr(reg) });
}
private static void WinThreadStopTextInput(CmdTextInputStop cmd)
{
SDL.SDL_StopTextInput(cmd.Window);
}
public void ClipboardSetText(WindowReg mainWindow, string text)
{
SendCmd(new CmdSetClipboard { Text = text });
}
private void WinThreadSetClipboard(CmdSetClipboard cmd)
{
var res = SDL.SDL_SetClipboardText(cmd.Text);
if (res)
_sawmill.Error("Failed to set clipboard text: {error}", SDL.SDL_GetError());
}
public Task<string> ClipboardGetText(WindowReg mainWindow)
{
var tcs = new TaskCompletionSource<string>();
SendCmd(new CmdGetClipboard { Tcs = tcs });
return tcs.Task;
}
private static void WinThreadGetClipboard(CmdGetClipboard cmd)
{
cmd.Tcs.TrySetResult(SDL.SDL_GetClipboardText());
}
private static void CheckWindowDisposed(WindowReg reg)
{
if (reg.IsDisposed)
throw new ObjectDisposedException("Window disposed");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static nint WinPtr(WindowReg reg) => ((Sdl3WindowReg)reg).Sdl3Window;
private WindowReg? FindWindow(uint windowId)
{
foreach (var windowReg in _clyde._windows)
{
var glfwReg = (Sdl3WindowReg)windowReg;
if (glfwReg.WindowId == windowId)
return windowReg;
}
return null;
}
private sealed class Sdl3WindowReg : WindowReg
{
public nint Sdl3Window;
public uint WindowId;
public nint GlContext;
#pragma warning disable CS0649
public bool Fullscreen;
#pragma warning restore CS0649
public int SwapInterval;
// Kept around to avoid it being GCd.
public CursorImpl? Cursor;
public nint WindowsHwnd;
public nint X11Display;
public uint X11Id;
}
}
}

View File

@@ -1,105 +0,0 @@
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Robust.Client.Utility;
using SDL3;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using TerraFX.Interop.Windows;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed unsafe partial class Sdl3WindowingImpl
{
// Experimentally on my system, SM_CXICON is 32.
// I doubt MS is ever changing that, so...
// I wish SDL would take care of this instead of us having to figure out what the "main" icon is. Ugh.
private const int MainWindowIconSize = 32;
// Writing this out like this makes me realize we're spending multiple hundred KBs on storing the window icon.
// You know, come to think about it, what if we used LZ4 or Zstd to compress the window icon stored here?
// This is absolutely not worth the optimization but hilarious for me to think about.
// The surface used for the window icon.
// This may store additional surfaces as alternate forms.
private nint _windowIconSurface;
// The data for all the window icons surfaces.
// Must be kept around! Pinned!
// ReSharper disable once CollectionNeverQueried.Local
private byte[][]? _windowIconData;
private void LoadWindowIcons()
{
// Sort such that closest to 64 is first.
// SDL3 doesn't "figure it out itself" as much as GLFW does, which sucks.
var icons = _clyde.LoadWindowIcons().OrderBy(i => Math.Abs(i.Width - MainWindowIconSize)).ToArray();
if (icons.Length == 0)
{
// No window icons at all!
return;
}
_windowIconData = new byte[icons.Length][];
var mainImg = icons[0];
_sawmill.Verbose(
"Have {iconCount} window icons available, choosing {mainIconWidth}x{mainIconHeight} as main",
icons.Length,
mainImg.Width,
mainImg.Height);
(_windowIconSurface, var mainData) = CreateSurfaceFromImage(mainImg);
_windowIconData[0] = mainData;
for (var i = 1; i < icons.Length; i++)
{
var (surface, data) = CreateSurfaceFromImage(icons[i]);
_windowIconData[i] = data;
SDL.SDL_AddSurfaceAlternateImage(_windowIconSurface, surface);
// Kept alive by the main surface.
SDL.SDL_DestroySurface(surface);
}
return;
static (nint, byte[]) CreateSurfaceFromImage(Image<Rgba32> img)
{
var span = MemoryMarshal.AsBytes(img.GetPixelSpan());
var copied = GC.AllocateUninitializedArray<byte>(span.Length, pinned: true);
span.CopyTo(copied);
IntPtr surface;
fixed (byte* ptr = copied)
{
surface = SDL.SDL_CreateSurfaceFrom(
img.Width,
img.Height,
SDL.SDL_PixelFormat.SDL_PIXELFORMAT_ABGR8888,
(IntPtr)ptr,
sizeof(Rgba32) * img.Width);
}
return (surface, copied);
}
}
private void DestroyWindowIcons()
{
SDL.SDL_DestroySurface(_windowIconSurface);
_windowIconSurface = 0;
_windowIconData = null;
}
private void AssignWindowIconToWindow(nint window)
{
if (_windowIconSurface == 0)
return;
SDL.SDL_SetWindowIcon(window, (nint) _windowIconSurface);
}
}
}

View File

@@ -1,226 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using SDL3;
using DependencyAttribute = Robust.Shared.IoC.DependencyAttribute;
namespace Robust.Client.Graphics.Clyde;
internal partial class Clyde
{
private sealed partial class Sdl3WindowingImpl : IWindowingImpl
{
[Dependency] private readonly ILogManager _logManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
private readonly Clyde _clyde;
private GCHandle _selfGCHandle;
private readonly ISawmill _sawmill;
private readonly ISawmill _sawmillSdl3;
private SdlVideoDriver _videoDriver;
public Sdl3WindowingImpl(Clyde clyde, IDependencyCollection deps)
{
_clyde = clyde;
deps.InjectDependencies(this, true);
_sawmill = _logManager.GetSawmill("clyde.win");
_sawmillSdl3 = _logManager.GetSawmill("clyde.win.sdl3");
}
public bool Init()
{
InitChannels();
if (!InitSdl3())
return false;
return true;
}
private unsafe bool InitSdl3()
{
CheckThreadApartment();
_selfGCHandle = GCHandle.Alloc(this, GCHandleType.Normal);
SDL.SDL_SetLogPriorities(SDL.SDL_LogPriority.SDL_LOG_PRIORITY_VERBOSE);
SDL.SDL_SetLogOutputFunction(&LogOutputFunction, (void*) GCHandle.ToIntPtr(_selfGCHandle));
SDL.SDL_SetHint(SDL.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
SDL.SDL_SetHint(SDL.SDL_HINT_IME_IMPLEMENTED_UI, "composition");
// SDL3's GameInput support is currently broken and leaving it on
// causes a "that operation is not supported" error to be logged on startup.
// https://github.com/libsdl-org/SDL/issues/11813
SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_GAMEINPUT, "0");
var res = SDL.SDL_Init(SDL.SDL_InitFlags.SDL_INIT_VIDEO | SDL.SDL_InitFlags.SDL_INIT_EVENTS);
if (!res)
{
_sawmill.Fatal("Failed to initialize SDL3: {error}", SDL.SDL_GetError());
return false;
}
var version = SDL.SDL_GetVersion();
var videoDriver = SDL.SDL_GetCurrentVideoDriver();
_sawmill.Debug(
"SDL3 initialized, version: {major}.{minor}.{patch}, video driver: {videoDriver}",
SDL.SDL_VERSIONNUM_MAJOR(version),
SDL.SDL_VERSIONNUM_MINOR(version),
SDL.SDL_VERSIONNUM_MICRO(version),
videoDriver);
LoadSdl3VideoDriver();
_sdlEventWakeup = SDL.SDL_RegisterEvents(1);
if (_sdlEventWakeup == 0)
throw new InvalidOperationException("SDL_RegisterEvents failed");
LoadWindowIcons();
InitCursors();
InitMonitors();
ReloadKeyMap();
SDL.SDL_AddEventWatch(&EventWatch, (void*) GCHandle.ToIntPtr(_selfGCHandle));
return true;
}
private void CheckThreadApartment()
{
if (!OperatingSystem.IsWindows())
return;
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
_sawmill.Error("Thread apartment state isn't STA. This will likely break things!!!");
}
private void LoadSdl3VideoDriver()
{
_videoDriver = SDL.SDL_GetCurrentVideoDriver() switch
{
"windows" => SdlVideoDriver.Windows,
"x11" => SdlVideoDriver.X11,
_ => SdlVideoDriver.Other,
};
}
public unsafe void Shutdown()
{
if (_selfGCHandle != default)
{
SDL.SDL_RemoveEventWatch(&EventWatch, (void*) GCHandle.ToIntPtr(_selfGCHandle));
_selfGCHandle.Free();
_selfGCHandle = default;
}
SDL.SDL_SetLogOutputFunction(null, null);
if (SDL.SDL_WasInit(0) != 0)
{
_sawmill.Debug("Terminating SDL3");
SDL.SDL_Quit();
}
}
public void FlushDispose()
{
// Not currently used
}
public void GLMakeContextCurrent(WindowReg? reg)
{
SDL.SDLBool res;
if (reg is Sdl3WindowReg sdlReg)
res = SDL.SDL_GL_MakeCurrent(sdlReg.Sdl3Window, sdlReg.GlContext);
else
res = SDL.SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero);
if (!res)
_sawmill.Error("SDL_GL_MakeCurrent failed: {error}", SDL.SDL_GetError());
}
public void GLSwapInterval(WindowReg reg, int interval)
{
((Sdl3WindowReg)reg).SwapInterval = interval;
SDL.SDL_GL_SetSwapInterval(interval);
}
public unsafe void* GLGetProcAddress(string procName)
{
return (void*) SDL.SDL_GL_GetProcAddress(procName);
}
public string GetDescription()
{
var version = SDL.SDL_GetVersion();
var major = SDL.SDL_VERSIONNUM_MAJOR(version);
var minor = SDL.SDL_VERSIONNUM_MINOR(version);
var micro = SDL.SDL_VERSIONNUM_MICRO(version);
var videoDriver = SDL.SDL_GetCurrentVideoDriver();
var revision = SDL.SDL_GetRevision();
return $"SDL {major}.{minor}.{micro} (rev: {revision}, video driver: {videoDriver})";
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static unsafe void LogOutputFunction(
void* userdata,
int category,
SDL.SDL_LogPriority priority,
byte* message)
{
var obj = (Sdl3WindowingImpl) GCHandle.FromIntPtr((IntPtr)userdata).Target!;
var level = priority switch
{
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_VERBOSE => LogLevel.Verbose,
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_DEBUG => LogLevel.Debug,
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_INFO => LogLevel.Info,
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_WARN => LogLevel.Warning,
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_ERROR => LogLevel.Error,
SDL.SDL_LogPriority.SDL_LOG_PRIORITY_CRITICAL => LogLevel.Fatal,
_ => LogLevel.Error
};
var msg = Marshal.PtrToStringUTF8((IntPtr) message) ?? "";
var categoryName = SdlLogCategoryName(category);
obj._sawmillSdl3.Log(level, $"[{categoryName}] {msg}");
}
private static string SdlLogCategoryName(int category)
{
return (SDL.SDL_LogCategory) category switch {
// @formatter:off
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_APPLICATION => "application",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_ERROR => "error",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_ASSERT => "assert",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_SYSTEM => "system",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_AUDIO => "audio",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_VIDEO => "video",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_RENDER => "render",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_INPUT => "input",
SDL.SDL_LogCategory.SDL_LOG_CATEGORY_TEST => "test",
_ => "unknown"
// @formatter:on
};
}
private enum SdlVideoDriver
{
// These are the ones we need to be able to check against.
Other,
Windows,
X11
}
}
}

View File

@@ -2,10 +2,7 @@
using System.Runtime.InteropServices;
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.Utility;
using TerraFX.Interop.Windows;
using TerraFX.Interop.Xlib;
using X11Window = TerraFX.Interop.Xlib.Window;
namespace Robust.Client.Graphics.Clyde;
@@ -36,8 +33,6 @@ internal partial class Clyde
public static unsafe void WindowsSharedWindowCreate(HWND hWnd, IConfigurationManager cfg)
{
// TODO: REMOVE, only used by GLFW, SDL3 does DWMWA_USE_IMMERSIVE_DARK_MODE automatically.
// >= Windows 11 22000 check
if (cfg.GetCVar(CVars.DisplayWin11ImmersiveDarkMode) && Environment.OSVersion.Version.Build >= 22000)
{
@@ -45,37 +40,5 @@ internal partial class Clyde
Windows.DwmSetWindowAttribute(hWnd, 20, &b, (uint) sizeof(BOOL));
}
}
public static void SetWindowStyleNoTitleOptionsWindows(HWND hWnd)
{
DebugTools.Assert(hWnd != HWND.NULL);
Windows.SetWindowLongPtrW(
hWnd,
GWL.GWL_STYLE,
// Cast to long here to work around a bug in rider with nint bitwise operators.
(nint)((long)Windows.GetWindowLongPtrW(hWnd, GWL.GWL_STYLE) & ~WS.WS_SYSMENU));
}
public static unsafe void SetWindowStyleNoTitleOptionsX11(Display* x11Display, X11Window x11Window)
{
DebugTools.Assert(x11Window != X11Window.NULL);
// https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html#idm46181547486832
var newPropValString = Marshal.StringToCoTaskMemUTF8("_NET_WM_WINDOW_TYPE_DIALOG");
var newPropVal = Xlib.XInternAtom(x11Display, (sbyte*)newPropValString, Xlib.False);
DebugTools.Assert(newPropVal != Atom.NULL);
var propNameString = Marshal.StringToCoTaskMemUTF8("_NET_WM_WINDOW_TYPE");
#pragma warning disable CA1806
// [display] [window] [property] [type] [format (8, 16,32)] [mode] [data] [element count]
Xlib.XChangeProperty(x11Display, x11Window,
Xlib.XInternAtom(x11Display, (sbyte*)propNameString, Xlib.False), // should never be null; part of spec
Xlib.XA_ATOM, 32, Xlib.PropModeReplace,
(byte*)&newPropVal, 1);
#pragma warning restore CA1806
Marshal.FreeCoTaskMem(newPropValString);
Marshal.FreeCoTaskMem(propNameString);
}
}
}

View File

@@ -211,8 +211,6 @@ namespace Robust.Client.Graphics
public abstract void DrawLine(Vector2 from, Vector2 to, Color color);
public abstract void RenderInRenderTarget(IRenderTarget target, Action a, Color? clearColor);
public abstract void DrawTexture(Texture texture, Vector2 position, Color? modulate = null);
}
/// <summary>

View File

@@ -92,7 +92,7 @@ namespace Robust.Client.Graphics
public abstract void DrawTextureRectRegion(Texture texture, UIBox2 rect, UIBox2? subRegion = null, Color? modulate = null);
public override void DrawTexture(Texture texture, Vector2 position, Color? modulate = null)
public void DrawTexture(Texture texture, Vector2 position, Color? modulate = null)
{
CheckDisposed();

View File

@@ -74,7 +74,7 @@ namespace Robust.Client.Graphics
/// <remarks>
/// The sprite will have it's local dimensions calculated so that it has <see cref="EyeManager.PixelsPerMeter"/> texels per meter in the world.
/// </remarks>
public override void DrawTexture(Texture texture, Vector2 position, Color? modulate = null)
public void DrawTexture(Texture texture, Vector2 position, Color? modulate = null)
{
CheckDisposed();

View File

@@ -53,7 +53,7 @@ namespace Robust.Client.Graphics
/// <param name="fallback">If the character is not available, render "<22>" instead.</param>
/// <returns>How much to advance the cursor to draw the next character.</returns>
public abstract float DrawChar(
DrawingHandleBase handle, Rune rune, Vector2 baseline, float scale,
DrawingHandleScreen handle, Rune rune, Vector2 baseline, float scale,
Color color, bool fallback=true);
/// <summary>
@@ -109,7 +109,7 @@ namespace Robust.Client.Graphics
public override int GetDescent(float scale) => Handle.GetDescent(scale);
public override int GetLineHeight(float scale) => Handle.GetLineHeight(scale);
public override float DrawChar(DrawingHandleBase handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
public override float DrawChar(DrawingHandleScreen handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
{
var metrics = Handle.GetCharMetrics(rune, scale);
if (!metrics.HasValue)
@@ -132,10 +132,7 @@ namespace Robust.Client.Graphics
}
baseline += new Vector2(metrics.Value.BearingX, -metrics.Value.BearingY);
if(handle is DrawingHandleWorld worldhandle)
worldhandle.DrawTextureRect(texture, Box2.FromDimensions(baseline, texture.Size), color);
else
handle.DrawTexture(texture, baseline, color);
handle.DrawTexture(texture, baseline, color);
return metrics.Value.Advance;
}
@@ -172,7 +169,7 @@ namespace Robust.Client.Graphics
public override int GetLineHeight(float scale) => _main.GetLineHeight(scale);
// DrawChar just proxies to the stack, or invokes _main's fallback.
public override float DrawChar(DrawingHandleBase handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
public override float DrawChar(DrawingHandleScreen handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
{
foreach (var f in Stack)
{
@@ -210,7 +207,7 @@ namespace Robust.Client.Graphics
public override int GetDescent(float scale) => default;
public override int GetLineHeight(float scale) => default;
public override float DrawChar(DrawingHandleBase handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
public override float DrawChar(DrawingHandleScreen handle, Rune rune, Vector2 baseline, float scale, Color color, bool fallback=true)
{
// Nada, it's a dummy after all.
return 0;

View File

@@ -133,5 +133,29 @@ namespace Robust.Client.Graphics
IEnumerable<IClydeMonitor> EnumerateMonitors();
IClydeWindow CreateWindow(WindowCreateParameters parameters);
/// <summary>
/// Set the active text input area in window pixel coordinates.
/// </summary>
/// <param name="rect">
/// This information is used by the OS to position overlays like IMEs or emoji pickers etc.
/// </param>
void TextInputSetRect(UIBox2i rect);
/// <summary>
/// Indicate that the game should start accepting text input on the currently focused window.
/// </summary>
/// <remarks>
/// On some platforms, this will cause an on-screen keyboard to appear.
/// The game will also start accepting IME input if configured by the user.
/// </remarks>
/// <seealso cref="TextInputStop"/>
void TextInputStart();
/// <summary>
/// Stop text input, opposite of <see cref="TextInputStart"/>.
/// </summary>
/// <seealso cref="TextInputStart"/>
void TextInputStop();
}
}

View File

@@ -69,7 +69,5 @@ namespace Robust.Client.Graphics
void ShutdownGridEcsEvents();
void RunOnWindowThread(Action action);
IFileDialogManager? FileDialogImpl { get; }
}
}

View File

@@ -66,7 +66,7 @@ namespace Robust.Client.Graphics
/// Not relative to the current transform of <see cref="handle"/>.
/// </param>
public void RenderScreenOverlaysBelow(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds);
@@ -80,7 +80,7 @@ namespace Robust.Client.Graphics
/// Not relative to the current transform of <see cref="handle"/>.
/// </param>
public void RenderScreenOverlaysAbove(
IRenderHandle handle,
DrawingHandleScreen handle,
IViewportControl control,
in UIBox2i viewportBounds);
}

View File

@@ -41,30 +41,6 @@ namespace Robust.Client.Graphics
/// Raised when the window has been resized.
/// </summary>
event Action<WindowResizedEventArgs> Resized;
/// <summary>
/// Set the active text input area in window pixel coordinates.
/// </summary>
/// <param name="rect">
/// This information is used by the OS to position overlays like IMEs or emoji pickers etc.
/// </param>
void TextInputSetRect(UIBox2i rect, int cursor);
/// <summary>
/// Indicate that the game should start accepting text input on the currently focused window.
/// </summary>
/// <remarks>
/// On some platforms, this will cause an on-screen keyboard to appear.
/// The game will also start accepting IME input if configured by the user.
/// </remarks>
/// <seealso cref="TextInputStop"/>
void TextInputStart();
/// <summary>
/// Stop text input, opposite of <see cref="TextInputStart"/>.
/// </summary>
/// <seealso cref="TextInputStart"/>
void TextInputStop();
}
public interface IClydeWindowInternal : IClydeWindow

View File

@@ -54,29 +54,23 @@ namespace Robust.Client.Graphics
/// </summary>
public readonly Box2Rotated WorldBounds;
public readonly IRenderHandle RenderHandle;
public DrawingHandleScreen ScreenHandle => (DrawingHandleScreen) DrawingHandle;
public DrawingHandleWorld WorldHandle => (DrawingHandleWorld) DrawingHandle;
internal OverlayDrawArgs(
public OverlayDrawArgs(
OverlaySpace space,
IViewportControl? viewportControl,
IClydeViewport viewport,
IRenderHandle renderHandle,
DrawingHandleBase drawingHandle,
in UIBox2i viewportBounds,
in MapId mapId,
in Box2 worldAabb,
in Box2Rotated worldBounds)
{
DrawingHandle = space is OverlaySpace.ScreenSpace or OverlaySpace.ScreenSpaceBelowWorld
? renderHandle.DrawingHandleScreen
: renderHandle.DrawingHandleWorld;
Space = space;
ViewportControl = viewportControl;
Viewport = viewport;
RenderHandle = renderHandle;
DrawingHandle = drawingHandle;
ViewportBounds = viewportBounds;
MapId = mapId;
WorldAABB = worldAabb;

View File

@@ -13,22 +13,10 @@ internal sealed class OverlayManager : IOverlayManagerInternal, IPostInjectInit
[Dependency] private readonly ILogManager _logMan = default!;
[ViewVariables]
private readonly Dictionary<Type, Overlay> _overlays = new();
/// <summary>
/// A list that duplicates a value from <see cref="_overlays"/>,
/// but already sorted, by invoking <see cref="Sort"/>
/// in <see cref="AddOverlay"/> and <see cref="RemoveOverlay(System.Type)"/>.
/// </summary>
[ViewVariables]
private readonly List<Overlay> _sortedOverlays = [];
private readonly Dictionary<Type, Overlay> _overlays = new Dictionary<Type, Overlay>();
private ISawmill _logger = default!;
/// <summary>
/// Returns a list of all overlays sorted by <see cref="Overlay.ZIndex"/>
/// </summary>
public IEnumerable<Overlay> AllOverlays => _sortedOverlays;
public IEnumerable<Overlay> AllOverlays => _overlays.Values;
public void FrameUpdate(FrameEventArgs args)
{
@@ -40,10 +28,9 @@ internal sealed class OverlayManager : IOverlayManagerInternal, IPostInjectInit
public bool AddOverlay(Overlay overlay)
{
if (!_overlays.TryAdd(overlay.GetType(), overlay))
if (_overlays.ContainsKey(overlay.GetType()))
return false;
Sort();
_overlays.Add(overlay.GetType(), overlay);
return true;
}
@@ -55,9 +42,7 @@ internal sealed class OverlayManager : IOverlayManagerInternal, IPostInjectInit
return false;
}
var result = _overlays.Remove(overlayClass);
Sort();
return result;
return _overlays.Remove(overlayClass);
}
public bool RemoveOverlay<T>() where T : Overlay
@@ -67,7 +52,7 @@ internal sealed class OverlayManager : IOverlayManagerInternal, IPostInjectInit
public bool RemoveOverlay(Overlay overlay)
{
return RemoveOverlay(overlay.GetType());
return _overlays.Remove(overlay.GetType());
}
public bool TryGetOverlay(Type overlayClass, [NotNullWhen(true)] out Overlay? overlay)
@@ -119,27 +104,8 @@ internal sealed class OverlayManager : IOverlayManagerInternal, IPostInjectInit
return _overlays.ContainsKey(typeof(T));
}
private void Sort()
{
_sortedOverlays.Clear();
_sortedOverlays.AddRange(_overlays.Values);
_sortedOverlays.Sort(OverlayComparer.Instance);
}
void IPostInjectInit.PostInject()
{
_logger = _logMan.GetSawmill("overlay");
}
private sealed class OverlayComparer : IComparer<Overlay>
{
public static readonly OverlayComparer Instance = new();
public int Compare(Overlay? x, Overlay? y)
{
var zX = x?.ZIndex ?? 0;
var zY = y?.ZIndex ?? 0;
return zX.CompareTo(zY);
}
}
}

View File

@@ -13,9 +13,8 @@ namespace Robust.Client.Physics
internal sealed class GridFixtureSystem : SharedGridFixtureSystem
{
[Dependency] private readonly IOverlayManager _overlay = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IMapManager _map = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly SharedMapSystem _map = default!;
public bool EnableDebug
{
@@ -29,7 +28,7 @@ namespace Robust.Client.Physics
if (_enableDebug)
{
var overlay = new GridSplitNodeOverlay(_mapManager, this, _transform, _map);
var overlay = new GridSplitNodeOverlay(_map, this, _transform);
_overlay.AddOverlay(overlay);
RaiseNetworkEvent(new RequestGridNodesMessage());
}
@@ -75,14 +74,12 @@ namespace Robust.Client.Physics
private readonly IMapManager _mapManager;
private readonly GridFixtureSystem _system;
private readonly SharedTransformSystem _transform;
private readonly SharedMapSystem _map;
public GridSplitNodeOverlay(IMapManager mapManager, GridFixtureSystem system, SharedTransformSystem transform, SharedMapSystem map)
public GridSplitNodeOverlay(IMapManager mapManager, GridFixtureSystem system, SharedTransformSystem transform)
{
_mapManager = mapManager;
_system = system;
_transform = transform;
_map = map;
}
protected internal override void Draw(in OverlayDrawArgs args)
@@ -92,7 +89,7 @@ namespace Robust.Client.Physics
var state = (_system, _transform, args.WorldBounds, worldHandle);
_mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds, ref state,
(EntityUid uid, MapGridComponent grid,
static (EntityUid uid, MapGridComponent grid,
ref (GridFixtureSystem system, SharedTransformSystem transform, Box2Rotated worldBounds, DrawingHandleWorld worldHandle) tuple) =>
{
// May not have received nodes yet.
@@ -100,7 +97,7 @@ namespace Robust.Client.Physics
return true;
tuple.worldHandle.SetTransform(tuple.transform.GetWorldMatrix(uid));
var chunkEnumerator = _map.GetMapChunks(uid, grid, tuple.worldBounds);
var chunkEnumerator = grid.GetMapChunks(tuple.worldBounds);
while (chunkEnumerator.MoveNext(out var chunk))
{

View File

@@ -93,7 +93,7 @@ public sealed partial class PhysicsSystem
var maps = new HashSet<EntityUid>();
var enumerator = AllEntityQuery<PredictedPhysicsComponent, PhysicsComponent, TransformComponent>();
while (enumerator.MoveNext(out _, out var physics, out var xform))
while (enumerator.MoveNext(out var _, out var physics, out var xform))
{
DebugTools.Assert(physics.Predict);

View File

@@ -25,9 +25,7 @@ namespace Robust.Client.Placement.Modes
{
var viewportSize = (Vector2)pManager.Clyde.ScreenSize;
var gridUid = pManager.EntityManager.System<SharedTransformSystem>().GetGrid(MouseCoords);
var gridPosition = pManager.EntityManager.System<SharedMapSystem>().MapToGrid(gridUid!.Value, pManager.EyeManager.ScreenToMap(Vector2.Zero));
var gridPosition = Grid.MapToGrid(pManager.EyeManager.ScreenToMap(Vector2.Zero));
var gridstart = pManager.EyeManager.CoordinatesToScreen(
gridPosition.WithPosition(new Vector2(MathF.Floor(gridPosition.X), MathF.Floor(gridPosition.Y))));
@@ -54,9 +52,9 @@ namespace Robust.Client.Placement.Modes
{
MouseCoords = ScreenToCursorGrid(mouseScreen);
var gridIdOpt = pManager.EntityManager.System<SharedTransformSystem>().GetGrid(MouseCoords);
var gridIdOpt = MouseCoords.GetGridUid(pManager.EntityManager);
SnapSize = 1f;
if (gridIdOpt is { } gridId && gridId.IsValid())
if (gridIdOpt is EntityUid gridId && gridId.IsValid())
{
Grid = pManager.EntityManager.GetComponent<MapGridComponent>(gridId);
SnapSize = Grid.TileSize; //Find snap size for the grid.

View File

@@ -27,7 +27,6 @@ namespace Robust.Client.Placement
{
public sealed partial class PlacementManager : IPlacementManager, IDisposable, IEntityEventSubscriber
{
[Dependency] private readonly ILogManager _logManager = default!;
[Dependency] private readonly IClientNetManager _networkManager = default!;
[Dependency] internal readonly IPlayerManager PlayerManager = default!;
[Dependency] internal readonly IResourceCache ResourceCache = default!;
@@ -43,11 +42,6 @@ namespace Robust.Client.Placement
[Dependency] private readonly IOverlayManager _overlayManager = default!;
[Dependency] internal readonly IClyde Clyde = default!;
private ISawmill _sawmill = default!;
private SharedMapSystem Maps => EntityManager.System<SharedMapSystem>();
private SharedTransformSystem XformSystem => EntityManager.System<SharedTransformSystem>();
/// <summary>
/// How long before a pending tile change is dropped.
/// </summary>
@@ -194,7 +188,6 @@ namespace Robust.Client.Placement
public void Initialize()
{
_drawingShader = _prototypeManager.Index<ShaderPrototype>("unshaded").Instance();
_sawmill = _logManager.GetSawmill("placement");
_networkManager.RegisterNetMessage<MsgPlacement>(HandlePlacementMessage);
@@ -344,11 +337,7 @@ namespace Robust.Client.Placement
private void HandleTileChanged(ref TileChangedEvent args)
{
var coords = Maps.GridTileToLocal(
args.NewTile.GridUid,
EntityManager.GetComponent<MapGridComponent>(args.NewTile.GridUid),
args.NewTile.GridIndices);
var coords = EntityManager.GetComponent<MapGridComponent>(args.NewTile.GridUid).GridTileToLocal(args.NewTile.GridIndices);
_pendingTileChanges.RemoveAll(c => c.Item1 == coords);
}
@@ -486,7 +475,7 @@ namespace Robust.Client.Placement
if (!_modeDictionary.TryFirstOrNull(pair => pair.Key.Equals(CurrentPermission.PlacementOption), out KeyValuePair<string, Type>? placeMode))
{
_sawmill.Log(LogLevel.Warning, $"Invalid placement mode `{CurrentPermission.PlacementOption}`");
Logger.LogS(LogLevel.Warning, nameof(PlacementManager), $"Invalid placement mode `{CurrentPermission.PlacementOption}`");
Clear();
return;
}
@@ -536,14 +525,14 @@ namespace Robust.Client.Placement
}
else
{
var mousePosition = EyeManager.PixelToMap(InputManager.MouseScreenPosition);
var map = EntityManager.GetComponent<TransformComponent>(ent).MapID;
if (map == MapId.Nullspace || !Eraser || mousePosition.MapId == MapId.Nullspace)
if (map == MapId.Nullspace || !Eraser)
{
coordinates = new EntityCoordinates();
return false;
}
coordinates = XformSystem.ToCoordinates(mousePosition);
coordinates = EntityCoordinates.FromMap(MapManager,
EyeManager.PixelToMap(InputManager.MouseScreenPosition));
return true;
}
}
@@ -659,7 +648,7 @@ namespace Robust.Client.Placement
PlayerManager.LocalEntity is not {Valid: true} controlled)
return;
var worldPos = XformSystem.GetWorldPosition(controlled);
var worldPos = EntityManager.GetComponent<TransformComponent>(controlled).WorldPosition;
args.WorldHandle.DrawCircle(worldPos, CurrentPermission.Range, new Color(1, 1, 1, 0.25f));
}
@@ -765,14 +754,14 @@ namespace Robust.Client.Placement
if (CurrentPermission.IsTile)
{
var gridIdOpt = XformSystem.GetGrid(coordinates);
var gridIdOpt = EntityManager.System<SharedTransformSystem>().GetGrid(coordinates);
// If we have actually placed something on a valid grid...
if (gridIdOpt is { } gridId && gridId.IsValid())
{
var grid = EntityManager.GetComponent<MapGridComponent>(gridId);
// no point changing the tile to the same thing.
if (Maps.GetTileRef(gridId, grid, coordinates).Tile.TypeId == CurrentPermission.TileType)
if (EntityManager.System<SharedMapSystem>().GetTileRef(gridId, grid, coordinates).Tile.TypeId == CurrentPermission.TileType)
return;
}

View File

@@ -352,9 +352,6 @@ public sealed partial class ReplayLoadManager
// prototype changes when jumping around in time. This also requires reworking how the initial
// implicit state data is generated, because we can't simply cache it anymore.
// Also, does reloading prototypes in release mode modify existing entities?
// Yes, yes it does. See PrototypeReloadSystem.UpdateEntity()
// Its just not supported ATM.
// TBH it'd be easier if overriding existing prototypes in release mode was just forbidden.
var msg = $"Overwriting an existing prototype! Kind: {kind.Name}. Ids: {string.Join(", ", ids)}";
if (_confMan.GetCVar(CVars.ReplayIgnoreErrors))
@@ -364,6 +361,7 @@ public sealed partial class ReplayLoadManager
}
}
_protoMan.ResolveResults();
_protoMan.ReloadPrototypes(changed);
_locMan.ReloadLocalizations();
}

View File

@@ -95,21 +95,9 @@ public sealed partial class ReplayLoadManager
_gameState.ClearDetachQueue();
_gameState.ApplyGameState(checkpoint.State, next);
// Sort entities to ensure that we initialize parents before children
var sorted = new List<EntityUid>(entities.Count);
var added = new HashSet<EntityUid>(entities.Count);
var xformQuery = _entMan.GetEntityQuery<TransformComponent>();
foreach (var uid in entities)
{
AddSorted(uid, sorted, added, xformQuery);
}
DebugTools.AssertEqual(sorted.Count, entities.Count);
DebugTools.AssertEqual(added.Count, entities.Count);
await callback(i, total, LoadingState.Initializing, false);
i = 0;
var query = _entMan.GetEntityQuery<MetaDataComponent>();
foreach (var uid in sorted)
foreach (var uid in entities)
{
_entMan.InitializeEntity(uid, query.GetComponent(uid));
if (i++ % 50 == 0)
@@ -121,7 +109,7 @@ public sealed partial class ReplayLoadManager
i = 0;
await callback(0, total, LoadingState.Starting, true);
foreach (var uid in sorted)
foreach (var uid in entities)
{
_entMan.StartEntity(uid);
if (i++ % 50 == 0)
@@ -144,16 +132,4 @@ public sealed partial class ReplayLoadManager
_replayPlayback.StartReplay(data);
_timing.Paused = false;
}
private void AddSorted(EntityUid uid, List<EntityUid> sortedList, HashSet<EntityUid> added, EntityQuery<TransformComponent> query)
{
if (!added.Add(uid))
return;
var parent = query.Comp(uid).ParentUid;
if (parent != EntityUid.Invalid)
AddSorted(parent, sortedList, added, query);
sortedList.Add(uid);
}
}

View File

@@ -45,7 +45,6 @@ internal sealed partial class ReplayPlaybackManager
var next = Replay.NextState;
BeforeApplyState?.Invoke((state, next));
_gameState.ApplyGameState(state, next);
_gameState.MergeImplicitData();
DebugTools.Assert(Replay.LastApplied >= state.FromSequence);
DebugTools.Assert(Replay.LastApplied + 1 <= state.ToSequence);
Replay.LastApplied = state.ToSequence;

View File

@@ -143,9 +143,9 @@ namespace Robust.Client.ResourceManagement
}
});
var atlasLookup = rsiList.ToLookup(ShouldMetaAtlas);
var atlasList = atlasLookup[true].ToArray();
var nonAtlasList = atlasLookup[false].ToArray();
// Do not meta-atlas RSIs with custom load parameters.
var atlasList = rsiList.Where(x => x.LoadParameters == TextureLoadParameters.Default).ToArray();
var nonAtlasList = rsiList.Where(x => x.LoadParameters != TextureLoadParameters.Default).ToArray();
foreach (var data in nonAtlasList)
{
@@ -225,9 +225,8 @@ namespace Robust.Client.ResourceManagement
void FinalizeMetaAtlas(int toIndex, Image<Rgba32> sheet)
{
var fromIndex = finalized + 1;
var atlas = Clyde.LoadTextureFromImage(sheet, $"Meta atlas {fromIndex}-{toIndex}");
for (int i = fromIndex; i <= toIndex; i++)
var atlas = Clyde.LoadTextureFromImage(sheet);
for (int i = finalized + 1; i <= toIndex; i++)
{
var rsi = atlasList[i];
rsi.AtlasTexture = atlas;
@@ -283,11 +282,7 @@ namespace Robust.Client.ResourceManagement
nonAtlasList.Length,
errors,
sw.Elapsed);
}
private static bool ShouldMetaAtlas(RSIResource.LoadStepData rsi)
{
return rsi.MetaAtlas && rsi.LoadParameters == TextureLoadParameters.Default;
}
}
}

View File

@@ -183,7 +183,6 @@ namespace Robust.Client.ResourceManagement
data.DimX = dimensionX;
data.CallbackOffsets = callbackOffsets;
data.LoadParameters = metadata.LoadParameters;
data.MetaAtlas = metadata.MetaAtlas;
}
internal static void LoadPostTexture(LoadStepData data)
@@ -387,7 +386,6 @@ namespace Robust.Client.ResourceManagement
public Vector2i AtlasOffset;
public RSI Rsi = default!;
public TextureLoadParameters LoadParameters;
public bool MetaAtlas;
}
internal struct StateReg

View File

@@ -21,15 +21,12 @@
<PackageReference Include="OpenTK.OpenAL" PrivateAssets="compile" />
<PackageReference Include="SpaceWizards.SharpFont" PrivateAssets="compile" />
<PackageReference Include="Robust.Natives" />
<PackageReference Include="System.Numerics.Vectors" />
<PackageReference Include="TerraFX.Interop.Windows" PrivateAssets="compile" />
<PackageReference Condition="'$(RobustToolsBuild)' == 'True'" Include="JetBrains.Profiler.Api" PrivateAssets="compile" />
<PackageReference Include="SpaceWizards.Sodium" PrivateAssets="compile" />
<PackageReference Include="Microsoft.NET.ILLink.Tasks" />
<PackageReference Include="TerraFX.Interop.Xlib" />
<!-- Needed to pin transitive dependency versions. -->
<PackageReference Include="System.Text.Json" />
<PackageReference Include="Newtonsoft.Json" />
</ItemGroup>
<ItemGroup Condition="'$(EnableClientScripting)' == 'True'">
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Features" PrivateAssets="compile" />

View File

@@ -1,5 +1,4 @@
using System;
using Robust.Client.GameObjects;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.GameObjects;
@@ -7,63 +6,14 @@ namespace Robust.Client.UserInterface;
public static class BoundUserInterfaceExt
{
private static T GetWindow<T>(BoundUserInterface bui) where T : BaseWindow, new()
{
var window = bui.CreateDisposableControl<T>();
window.OnClose += bui.Close;
var system = bui.EntMan.System<UserInterfaceSystem>();
system.RegisterControl(bui, window);
return window;
}
/// <summary>
/// Helper method to create a window and also handle closing the BUI when it's closed.
/// </summary>
public static T CreateWindow<T>(this BoundUserInterface bui) where T : BaseWindow, new()
{
var window = GetWindow<T>(bui);
if (bui.EntMan.System<UserInterfaceSystem>().TryGetPosition(bui.Owner, bui.UiKey, out var position))
{
window.Open(position);
}
else
{
window.OpenCentered();
}
return window;
}
public static T CreateWindowCenteredLeft<T>(this BoundUserInterface bui) where T : BaseWindow, new()
{
var window = GetWindow<T>(bui);
if (bui.EntMan.System<UserInterfaceSystem>().TryGetPosition(bui.Owner, bui.UiKey, out var position))
{
window.Open(position);
}
else
{
window.OpenCenteredLeft();
}
return window;
}
public static T CreateWindowCenteredRight<T>(this BoundUserInterface bui) where T : BaseWindow, new()
{
var window = GetWindow<T>(bui);
if (bui.EntMan.System<UserInterfaceSystem>().TryGetPosition(bui.Owner, bui.UiKey, out var position))
{
window.Open(position);
}
else
{
window.OpenCenteredRight();
}
var window = bui.CreateDisposableControl<T>();
window.OpenCentered();
window.OnClose += bui.Close;
return window;
}

View File

@@ -128,7 +128,7 @@ namespace Robust.Client.UserInterface
UserInterfaceManagerInternal.QueueStyleUpdate(this);
}
public void InvalidateStyleSheet()
internal void StyleSheetUpdate()
{
_stylesheetUpdateNeeded = true;
@@ -137,7 +137,7 @@ namespace Robust.Client.UserInterface
internal void StylesheetUpdateRecursive()
{
InvalidateStyleSheet();
StyleSheetUpdate();
foreach (var child in Children)
{
@@ -149,7 +149,7 @@ namespace Robust.Client.UserInterface
}
}
public void DoStyleUpdate()
internal void DoStyleUpdate()
{
_styleProperties.Clear();

View File

@@ -549,7 +549,7 @@ namespace Robust.Client.UserInterface
{
}
protected internal virtual void Draw(IRenderHandle renderHandle)
internal virtual void DrawInternal(IRenderHandle renderHandle)
{
Draw(renderHandle.DrawingHandleScreen);
}

View File

@@ -87,6 +87,7 @@ public sealed class TileSpawningUIController : UIController
return;
_window = UIManager.CreateWindow<TileSpawnWindow>();
LayoutContainer.SetAnchorPreset(_window,LayoutContainer.LayoutPreset.CenterLeft);
_window.SearchBar.GrabKeyboardFocus();
_window.ClearButton.OnPressed += OnTileClearPressed;
_window.SearchBar.OnTextChanged += OnTileSearchChanged;
_window.TileList.OnItemSelected += OnTileItemSelected;

Some files were not shown because too many files have changed in this diff Show More