diff --git a/sources/assets/Stride.Core.Assets.CompilerApp/PackageBuilderApp.cs b/sources/assets/Stride.Core.Assets.CompilerApp/PackageBuilderApp.cs index 9478eccd2e..a40486d9ec 100644 --- a/sources/assets/Stride.Core.Assets.CompilerApp/PackageBuilderApp.cs +++ b/sources/assets/Stride.Core.Assets.CompilerApp/PackageBuilderApp.cs @@ -84,7 +84,7 @@ public int Run(string[] args) { "log", "Enable file logging", v => options.EnableFileLogging = v != null }, { "disable-auto-compile", "Disable auto-compile of projects", v => options.DisableAutoCompileProjects = v != null}, { "project-configuration=", "Project configuration", v => options.ProjectConfiguration = v }, - { "platform=", "Platform name", v => options.Platform = (PlatformType)Enum.Parse(typeof(PlatformType), v) }, + { "platform=", "Platform name", v => options.Platform = Enum.Parse(v) }, { "solution-file=", "Solution File Name", v => options.SolutionFile = v }, { "package-id=", "Package Id from the solution file", v => options.PackageId = Guid.Parse(v) }, { "package-file=", "Input Package File Name", v => options.PackageFile = v }, diff --git a/sources/assets/Stride.Core.Assets/DefaultAssetFactory.cs b/sources/assets/Stride.Core.Assets/DefaultAssetFactory.cs index 7ed77c205e..3985dbaab1 100644 --- a/sources/assets/Stride.Core.Assets/DefaultAssetFactory.cs +++ b/sources/assets/Stride.Core.Assets/DefaultAssetFactory.cs @@ -12,7 +12,7 @@ public class DefaultAssetFactory : AssetFactory where T : Asset { public static T Create() { - return (T)Activator.CreateInstance(typeof(T))!; + return Activator.CreateInstance()!; } /// diff --git a/sources/assets/Stride.Core.Assets/PackageSession.cs b/sources/assets/Stride.Core.Assets/PackageSession.cs index ee463ff82a..c17421879c 100644 --- a/sources/assets/Stride.Core.Assets/PackageSession.cs +++ b/sources/assets/Stride.Core.Assets/PackageSession.cs @@ -1601,6 +1601,11 @@ public override bool Equals(object? obj) return Equals(obj as PendingPackageUpgrade); } + public override int GetHashCode() + { + return HashCode.Combine(PackageUpgrader, Dependency, DependencyPackage, DependencyVersionBeforeUpgrade); + } + public PendingPackageUpgrade Clone() { return new PendingPackageUpgrade(PackageUpgrader, Dependency.Clone(), DependencyPackage); diff --git a/sources/assets/Stride.Core.Assets/VSProjectHelper.cs b/sources/assets/Stride.Core.Assets/VSProjectHelper.cs index 6aaa3e5241..3ec73c626d 100644 --- a/sources/assets/Stride.Core.Assets/VSProjectHelper.cs +++ b/sources/assets/Stride.Core.Assets/VSProjectHelper.cs @@ -55,7 +55,7 @@ public static Guid GetProjectGuid(MicrosoftProject project) { return null; } - return (T)Enum.Parse(typeof(T), value); + return Enum.Parse(value); } public static string GetOrCompileProjectAssembly(string fullProjectLocation, ILogger logger, string targets, bool autoCompileProject, string configuration, string platform = "AnyCPU", Dictionary? extraProperties = null, bool onlyErrors = false, BuildRequestDataFlags flags = BuildRequestDataFlags.None) diff --git a/sources/buildengine/Stride.Core.BuildEngine.Common/StepCounter.cs b/sources/buildengine/Stride.Core.BuildEngine.Common/StepCounter.cs index a7cb0f9daa..7369f86bdd 100644 --- a/sources/buildengine/Stride.Core.BuildEngine.Common/StepCounter.cs +++ b/sources/buildengine/Stride.Core.BuildEngine.Common/StepCounter.cs @@ -10,7 +10,7 @@ public class StepCounter public StepCounter() { - stepResults = new int[Enum.GetValues(typeof(ResultStatus)).Length]; + stepResults = new int[Enum.GetValues().Length]; } public void AddStepResult(ResultStatus result) @@ -35,7 +35,7 @@ public void Clear() lock (stepResults) { Total = 0; - foreach (var value in Enum.GetValues(typeof(ResultStatus))) + foreach (var value in Enum.GetValues()) stepResults[(int)value] = 0; } } diff --git a/sources/core/Stride.Core.CompilerServices/Generators/ModuleInitializerGenerator.cs b/sources/core/Stride.Core.CompilerServices/Generators/ModuleInitializerGenerator.cs index e8595580c5..036fe8c3aa 100644 --- a/sources/core/Stride.Core.CompilerServices/Generators/ModuleInitializerGenerator.cs +++ b/sources/core/Stride.Core.CompilerServices/Generators/ModuleInitializerGenerator.cs @@ -58,6 +58,7 @@ private void Generate(SourceProductionContext context, ImmutableArray namespace Stride.Core.CompilerServices.AutoGenerated.ModuleInitializer {{ file static class ModuleInitializer diff --git a/sources/core/Stride.Core.Design.Tests/Collections/TestHybridDictionary.cs b/sources/core/Stride.Core.Design.Tests/Collections/TestHybridDictionary.cs index 3ddcf92b6d..81b427b550 100644 --- a/sources/core/Stride.Core.Design.Tests/Collections/TestHybridDictionary.cs +++ b/sources/core/Stride.Core.Design.Tests/Collections/TestHybridDictionary.cs @@ -102,7 +102,7 @@ public void Remove_ExistingKey_ShouldRemoveAndReturnTrue() var result = dictionary.Remove("key1"); Assert.True(result); - Assert.Equal(1, dictionary.Count); + Assert.Single(dictionary); Assert.False(dictionary.ContainsKey("key1")); } @@ -115,7 +115,7 @@ public void Remove_NonExistingKey_ShouldReturnFalse() var result = dictionary.Remove("key2"); Assert.False(result); - Assert.Equal(1, dictionary.Count); + Assert.Single(dictionary); } [Fact] @@ -202,7 +202,7 @@ public void Clear_WithItems_ShouldRemoveAllItems() dictionary.Clear(); - Assert.Equal(0, dictionary.Count); + Assert.Empty(dictionary); } [Fact] @@ -249,7 +249,7 @@ public void GetEnumerator_ShouldEnumerateAllItems() foreach (var kvp in dictionary) { count++; - Assert.True(kvp.Key.StartsWith("key")); + Assert.StartsWith("key", kvp.Key); } Assert.Equal(3, count); diff --git a/sources/core/Stride.Core.Mathematics.Tests/TestBoundingSphere.cs b/sources/core/Stride.Core.Mathematics.Tests/TestBoundingSphere.cs index bec9479626..d5b1f8c000 100644 --- a/sources/core/Stride.Core.Mathematics.Tests/TestBoundingSphere.cs +++ b/sources/core/Stride.Core.Mathematics.Tests/TestBoundingSphere.cs @@ -86,8 +86,8 @@ public void TestBoundingSphereMerge() BoundingSphere.Merge(ref sphere1, ref sphere2, out var merged); // Merged sphere should contain both spheres - Assert.True(merged.Contains(ref sphere1) != ContainmentType.Disjoint); - Assert.True(merged.Contains(ref sphere2) != ContainmentType.Disjoint); + Assert.NotEqual(ContainmentType.Disjoint, merged.Contains(ref sphere1)); + Assert.NotEqual(ContainmentType.Disjoint, merged.Contains(ref sphere2)); // Test non-ref version var merged2 = BoundingSphere.Merge(sphere1, sphere2); diff --git a/sources/core/Stride.Core.Mathematics.Tests/TestSphericalHarmonics.cs b/sources/core/Stride.Core.Mathematics.Tests/TestSphericalHarmonics.cs index cfe3e752a6..2c46d5814c 100644 --- a/sources/core/Stride.Core.Mathematics.Tests/TestSphericalHarmonics.cs +++ b/sources/core/Stride.Core.Mathematics.Tests/TestSphericalHarmonics.cs @@ -113,9 +113,9 @@ public void TestSphericalHarmonicsEvaluate_Order2() var result = sh.Evaluate(direction); // Verify result is valid (SH can produce negative or positive values) - Assert.True(!float.IsNaN(result.R)); - Assert.True(!float.IsNaN(result.G)); - Assert.True(!float.IsNaN(result.B)); + Assert.False(float.IsNaN(result.R)); + Assert.False(float.IsNaN(result.G)); + Assert.False(float.IsNaN(result.B)); } [Fact] diff --git a/sources/core/Stride.Core.Mathematics/Rectangle.cs b/sources/core/Stride.Core.Mathematics/Rectangle.cs index 859f83f8e4..0153470804 100644 --- a/sources/core/Stride.Core.Mathematics/Rectangle.cs +++ b/sources/core/Stride.Core.Mathematics/Rectangle.cs @@ -38,12 +38,7 @@ public struct Rectangle : IEquatable, ISpanFormattable /// /// An empty rectangle. /// - public static readonly Rectangle Empty; - - static Rectangle() - { - Empty = new Rectangle(); - } + public static readonly Rectangle Empty = new(); /// /// Initializes a new instance of the struct. diff --git a/sources/core/Stride.Core.Mathematics/RectangleF.cs b/sources/core/Stride.Core.Mathematics/RectangleF.cs index b24e4ce2b4..3ffc118b87 100644 --- a/sources/core/Stride.Core.Mathematics/RectangleF.cs +++ b/sources/core/Stride.Core.Mathematics/RectangleF.cs @@ -38,12 +38,7 @@ public struct RectangleF : IEquatable, ISpanFormattable /// /// An empty rectangle /// - public static readonly RectangleF Empty; - - static RectangleF() - { - Empty = new RectangleF(); - } + public static readonly RectangleF Empty = new(); /// /// Initializes a new instance of the struct. diff --git a/sources/core/Stride.Core.Serialization/IO/DatabaseFileProvider.cs b/sources/core/Stride.Core.Serialization/IO/DatabaseFileProvider.cs index ff9aee0158..71b137a65c 100644 --- a/sources/core/Stride.Core.Serialization/IO/DatabaseFileProvider.cs +++ b/sources/core/Stride.Core.Serialization/IO/DatabaseFileProvider.cs @@ -55,7 +55,7 @@ public override Stream OpenStream(string url, VirtualFileMode mode, VirtualFileA if (streamFlags == StreamFlags.Seekable && !result.CanSeek) { var buffer = new byte[result.Length - result.Position]; - result.Read(buffer, 0, buffer.Length); + result.ReadExactly(buffer, 0, buffer.Length); return new DatabaseReadFileStream(objectId, new MemoryStream(buffer), 0); } diff --git a/sources/core/Stride.Core.Serialization/IO/Store.cs b/sources/core/Stride.Core.Serialization/IO/Store.cs index bbf0039281..ef8568482c 100644 --- a/sources/core/Stride.Core.Serialization/IO/Store.cs +++ b/sources/core/Stride.Core.Serialization/IO/Store.cs @@ -323,7 +323,7 @@ private void RefreshData(long fileSize) return; var bufferToRead = new byte[length]; - stream.Read(bufferToRead, 0, length); + stream.ReadExactly(bufferToRead, 0, length); var memoryStream = new MemoryStream(bufferToRead); try diff --git a/sources/core/Stride.Core.Serialization/Storage/Blob.cs b/sources/core/Stride.Core.Serialization/Storage/Blob.cs index eb1d81f336..2761263b9d 100644 --- a/sources/core/Stride.Core.Serialization/Storage/Blob.cs +++ b/sources/core/Stride.Core.Serialization/Storage/Blob.cs @@ -32,7 +32,7 @@ internal unsafe Blob(ObjectDatabase objectDatabase, ObjectId objectId, Stream st { Size = (int)stream.Length; Content = Marshal.AllocHGlobal(Size); - stream.Read(new Span((void*)Content, Size)); + stream.ReadExactly(new Span((void*)Content, Size)); } /// diff --git a/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.cs b/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.cs index e770e764ca..9ac20aed08 100644 --- a/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.cs +++ b/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.cs @@ -5,6 +5,8 @@ namespace Stride.Core.Diagnostics; +#nullable enable + /// /// Extensions for . /// @@ -19,11 +21,7 @@ public static class LoggerExtensions /// Information about the caller. Default is null, otherwise use . public static void Verbose(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Verbose, message, exception, callerInfo)); } @@ -46,11 +44,7 @@ public static void Verbose(this ILogger logger, string message, CallerInfo? call /// Information about the caller. Default is null, otherwise use . public static void Debug(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Debug, message, exception, callerInfo)); } @@ -73,11 +67,7 @@ public static void Debug(this ILogger logger, string message, CallerInfo? caller /// Information about the caller. Default is null, otherwise use . public static void Info(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Info, message, exception, callerInfo)); } @@ -100,11 +90,7 @@ public static void Info(this ILogger logger, string message, CallerInfo? callerI /// Information about the caller. Default is null, otherwise use . public static void Warning(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Warning, message, exception, callerInfo)); } @@ -127,11 +113,7 @@ public static void Warning(this ILogger logger, string message, CallerInfo? call /// Information about the caller. Default is null, otherwise use . public static void Error(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Error, message, exception, callerInfo)); } @@ -154,11 +136,7 @@ public static void Error(this ILogger logger, string message, CallerInfo? caller /// Information about the caller. Default is null, otherwise use . public static void Fatal(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.Fatal, message, exception, callerInfo)); } diff --git a/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.tt b/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.tt index 902fe3cf24..7424070bbd 100644 --- a/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.tt +++ b/sources/core/Stride.Core/Diagnostics/ILogger.Extensions.tt @@ -11,6 +11,8 @@ namespace Stride.Core.Diagnostics; +#nullable enable + /// /// Extensions for . /// @@ -26,11 +28,7 @@ public static class LoggerExtensions /// Information about the caller. Default is null, otherwise use . public static void <#= name #>(this ILogger logger, string message, Exception? exception, CallerInfo? callerInfo = null) { -#if NET7_0_OR_GREATER ArgumentNullException.ThrowIfNull(logger); -#else - if (logger is null) throw new ArgumentNullException(nameof(logger)); -#endif // NET7_0_OR_GREATER logger.Log(new LogMessage(logger.Module, LogMessageType.<#= name #>, message, exception, callerInfo)); } diff --git a/sources/core/Stride.Core/Serialization/Serializers/CollectionSerializers.cs b/sources/core/Stride.Core/Serialization/Serializers/CollectionSerializers.cs index ef06c5b624..6cb4a411b0 100644 --- a/sources/core/Stride.Core/Serialization/Serializers/CollectionSerializers.cs +++ b/sources/core/Stride.Core/Serialization/Serializers/CollectionSerializers.cs @@ -323,7 +323,7 @@ public override unsafe void Serialize(ref T[] array, ArchiveMode mode, Serializa { var span = MemoryMarshal.Cast(array.AsSpan()); if (mode == ArchiveMode.Deserialize) - stream.UnderlyingStream.Read(span); + stream.UnderlyingStream.ReadExactly(span); else if (mode == ArchiveMode.Serialize) stream.UnderlyingStream.Write(span); } diff --git a/sources/editor/Stride.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EditorGameEntityTransformService.cs b/sources/editor/Stride.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EditorGameEntityTransformService.cs index c677b76ad2..ea187fb9cb 100644 --- a/sources/editor/Stride.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EditorGameEntityTransformService.cs +++ b/sources/editor/Stride.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EditorGameEntityTransformService.cs @@ -247,7 +247,7 @@ private async Task Update() if (game.Input.IsKeyPressed(SceneEditorSettings.SwitchGizmo.GetValue())) { var current = activeTransformation; - var next = (int)(current + 1) % Enum.GetValues(typeof(Transformation)).Length; + var next = (int)(current + 1) % Enum.GetValues().Length; await editor.Dispatcher.InvokeAsync(() => editor.Transform.ActiveTransformation = (Transformation)next); } } diff --git a/sources/editor/Stride.Assets.Presentation/AssetEditors/ProjectWatcher.cs b/sources/editor/Stride.Assets.Presentation/AssetEditors/ProjectWatcher.cs index 7088be174e..ce8d8723cb 100644 --- a/sources/editor/Stride.Assets.Presentation/AssetEditors/ProjectWatcher.cs +++ b/sources/editor/Stride.Assets.Presentation/AssetEditors/ProjectWatcher.cs @@ -290,7 +290,7 @@ private async Task FileChangeTransformation(FileEvent e) { using (var streamReader = new StreamReader(File.Open(changedFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8, true)) { - source = streamReader.ReadToEnd(); + source = await streamReader.ReadToEndAsync(); } break; } diff --git a/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.Diagnostics.cs b/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.Diagnostics.cs index 3e750d184c..16564f2b6f 100644 --- a/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.Diagnostics.cs +++ b/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.Diagnostics.cs @@ -79,7 +79,7 @@ private async Task TriggerBackgroundCompilation() SemanticModel = compilation.GetSemanticModel(syntaxTree); // Compute list of overridable methods - var type = SemanticModel.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType().FirstOrDefault()); + var type = SemanticModel.GetDeclaredSymbol((await syntaxTree.GetRootAsync()).DescendantNodes().OfType().FirstOrDefault()); // Note: Logic taken from Roslyn AbstractOverrideCompletionProvider var overridableMethodsCurrentType = new List(); @@ -123,7 +123,7 @@ private async Task TriggerBackgroundCompilation() // Find the syntax node that generated this diagnostic var sourceSpan = diagnostic.Location.SourceSpan; - var node = compileResult.SyntaxTree.GetRoot().FindNode(sourceSpan); + var node = (await compileResult.SyntaxTree.GetRootAsync()).FindNode(sourceSpan); // Find which block or link generated it // Go through parent recursively until we find one diff --git a/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.cs b/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.cs index b92b4b9fc5..01602c41a8 100644 --- a/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.cs +++ b/sources/editor/Stride.Assets.Presentation/AssetEditors/VisualScriptEditor/VisualScriptEditorViewModel.cs @@ -455,7 +455,7 @@ private void GenerateSymbolSearchValues(Compilation latestCompilation, Cancellat foreach (var assembly in GetAssemblies(latestCompilation, cancellationToken) .OrderBy(assembly => { - if (assembly == latestCompilation.Assembly) + if (SymbolEqualityComparer.Default.Equals(assembly, latestCompilation.Assembly)) return 0; if (assembly.Name.Contains("Stride")) @@ -471,11 +471,11 @@ private void GenerateSymbolSearchValues(Compilation latestCompilation, Cancellat // List types that are either public or part of current assembly foreach (var type in GetAllTypes(assembly, cancellationToken) - .Where(type => type.DeclaredAccessibility != RoslynAccessibility.Private || type.ContainingAssembly == latestCompilation.Assembly)) + .Where(type => type.DeclaredAccessibility != RoslynAccessibility.Private || SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, latestCompilation.Assembly))) { // List methods foreach (var method in type.GetMembers().OfType() - .Where(member => member.DeclaredAccessibility != RoslynAccessibility.Private || type.ContainingAssembly == latestCompilation.Assembly)) + .Where(member => member.DeclaredAccessibility != RoslynAccessibility.Private || SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, latestCompilation.Assembly))) { // Ignore .ctor, property getter/setter, events, etc... if (method.MethodKind != MethodKind.Ordinary @@ -522,7 +522,7 @@ private static IEnumerable GetAssemblies( CancellationToken cancellationToken) { var stack = new Stack(); - var processedAssemblies = new HashSet(); + var processedAssemblies = new HashSet(SymbolEqualityComparer.Default); processedAssemblies.Add(compilation.Assembly); stack.Push(compilation.Assembly); diff --git a/sources/editor/Stride.Assets.Presentation/Templates/ScriptTemplateGenerator.cs b/sources/editor/Stride.Assets.Presentation/Templates/ScriptTemplateGenerator.cs index 1fdc8f6bde..533fe3beb2 100644 --- a/sources/editor/Stride.Assets.Presentation/Templates/ScriptTemplateGenerator.cs +++ b/sources/editor/Stride.Assets.Presentation/Templates/ScriptTemplateGenerator.cs @@ -144,7 +144,7 @@ protected override IEnumerable CreateAssets(AssetTemplateGeneratorPar scriptContent = scriptContent.Replace("##Namespace##", parameters.Namespace); scriptContent = scriptContent.Replace("##Scriptname##", location.GetFileNameWithoutExtension()); - var asset = (ScriptSourceFileAsset)ObjectFactoryRegistry.NewInstance(typeof(ScriptSourceFileAsset)); + var asset = ObjectFactoryRegistry.NewInstance(); asset.Id = SourceCodeAsset.GenerateIdFromLocation(parameters.Package.Meta.Name, location); asset.Text = scriptContent; yield return new AssetItem(location, asset); diff --git a/sources/editor/Stride.Assets.Presentation/ViewModel/ScriptSourceFileAssetViewModel.cs b/sources/editor/Stride.Assets.Presentation/ViewModel/ScriptSourceFileAssetViewModel.cs index 9f1408ec86..ee0fdf7fc8 100644 --- a/sources/editor/Stride.Assets.Presentation/ViewModel/ScriptSourceFileAssetViewModel.cs +++ b/sources/editor/Stride.Assets.Presentation/ViewModel/ScriptSourceFileAssetViewModel.cs @@ -148,7 +148,7 @@ protected override async Task UpdateAssetFromSource(Logger logger) document = workspace.GetDocument(DocumentId.Result); // Set new text - TextDocument.Text = document.GetTextAsync().Result.ToString(); + TextDocument.Text = (await document.GetTextAsync()).ToString(); // Update dirty state hasExternalChanges = false; diff --git a/sources/editor/Stride.Core.Assets.Editor.Tests/TestCopyPasteProperties.cs b/sources/editor/Stride.Core.Assets.Editor.Tests/TestCopyPasteProperties.cs index c2e4536fda..8bf7b6274f 100644 --- a/sources/editor/Stride.Core.Assets.Editor.Tests/TestCopyPasteProperties.cs +++ b/sources/editor/Stride.Core.Assets.Editor.Tests/TestCopyPasteProperties.cs @@ -881,7 +881,7 @@ private void Paste([NotNull] Asset asset, string copiedText, Type deserializedTy var result = service.DeserializeCopiedData(copiedText, asset, expectedType); Assert.NotNull(result); Assert.NotNull(result.Items); - Assert.Equal(1, result.Items.Count); + Assert.Single(result.Items); var item = result.Items[0]; Assert.NotNull(item); diff --git a/sources/editor/Stride.Core.Assets.Editor/Components/Status/StatusViewModel.cs b/sources/editor/Stride.Core.Assets.Editor/Components/Status/StatusViewModel.cs index 832caff700..f8893dcfce 100644 --- a/sources/editor/Stride.Core.Assets.Editor/Components/Status/StatusViewModel.cs +++ b/sources/editor/Stride.Core.Assets.Editor/Components/Status/StatusViewModel.cs @@ -72,7 +72,7 @@ public void NotifyBackgroundJobFinished(int token) if (CurrentJob == job) { job = null; - foreach (JobPriority priority in Enum.GetValues(typeof(JobPriority)).Cast().Reverse()) + foreach (JobPriority priority in Enum.GetValues().Cast().Reverse()) { var nextJob = jobList.LastOrDefault(x => x.Value.Priority == priority).Value; if (nextJob != null) diff --git a/sources/editor/Stride.Core.Assets.Editor/ViewModel/AssetCollectionViewModel.cs b/sources/editor/Stride.Core.Assets.Editor/ViewModel/AssetCollectionViewModel.cs index 532e3e2230..36a3416c6f 100644 --- a/sources/editor/Stride.Core.Assets.Editor/ViewModel/AssetCollectionViewModel.cs +++ b/sources/editor/Stride.Core.Assets.Editor/ViewModel/AssetCollectionViewModel.cs @@ -166,7 +166,7 @@ public sealed class AssetFilterViewModelData // Storing out primitive data for filters to save between instances of editor private List StoredListData = InternalSettings.ViewFilters.GetValue(); - public static readonly IEnumerable AllFilterCategories = Enum.GetValues(typeof(FilterCategory)).Cast(); + public static readonly IEnumerable AllFilterCategories = Enum.GetValues(); private readonly ObservableSet assets = new ObservableSet(); diff --git a/sources/editor/Stride.GameStudio.Tests/TestCopyPasteComponents.cs b/sources/editor/Stride.GameStudio.Tests/TestCopyPasteComponents.cs index f6bd76ff23..d80fc5e2c5 100644 --- a/sources/editor/Stride.GameStudio.Tests/TestCopyPasteComponents.cs +++ b/sources/editor/Stride.GameStudio.Tests/TestCopyPasteComponents.cs @@ -64,7 +64,7 @@ private void Paste(AssetPropertyGraph propertyGraph, string copiedText, Type des var result = service.DeserializeCopiedData(copiedText, asset, expectedType); Assert.NotNull(result); Assert.NotNull(result.Items); - Assert.Equal(1, result.Items.Count); + Assert.Single(result.Items); var item = result.Items[0]; Assert.NotNull(item); diff --git a/sources/editor/Stride.GameStudio.Tests/TestCopyPasteWithEntities.cs b/sources/editor/Stride.GameStudio.Tests/TestCopyPasteWithEntities.cs index db528a087c..aead4b3317 100644 --- a/sources/editor/Stride.GameStudio.Tests/TestCopyPasteWithEntities.cs +++ b/sources/editor/Stride.GameStudio.Tests/TestCopyPasteWithEntities.cs @@ -137,7 +137,7 @@ private static void Paste([NotNull] ICopyPasteService service, string text, [Not var data = service.DeserializeCopiedData(text, assetGraph.Asset, typeof(Entity)); Assert.NotNull(data); Assert.NotNull(data.Items); - Assert.Equal(1, data.Items.Count); + Assert.Single(data.Items); var item = data.Items[0]; Assert.NotNull(item); diff --git a/sources/editor/Stride.GameStudio/Debugging/AssemblyRecompiler.cs b/sources/editor/Stride.GameStudio/Debugging/AssemblyRecompiler.cs index a03d789467..825cd6888a 100644 --- a/sources/editor/Stride.GameStudio/Debugging/AssemblyRecompiler.cs +++ b/sources/editor/Stride.GameStudio/Debugging/AssemblyRecompiler.cs @@ -23,7 +23,7 @@ namespace Stride.GameStudio.Debugging { public partial class AssemblyRecompiler { - private SourceGroup[] previousSortedConnectedGroups = new SourceGroup[0]; + private SourceGroup[] previousSortedConnectedGroups = []; private IMutableBidirectionalGraph, SourceGroup>> previousStronglyConnected = new BidirectionalGraph, SourceGroup>>(); private ImmutableHashSet previousConnectedGroups; private int assemblyCounter; @@ -53,7 +53,7 @@ public async Task Recompile(Project gameProject, LoggerResult logg foreach (var syntaxTree in gameProjectCompilation.SyntaxTrees) { - var syntaxRoot = syntaxTree.GetRoot(); + var syntaxRoot = await syntaxTree.GetRootAsync(); var semanticModel = gameProjectCompilation.GetSemanticModel(syntaxTree); var dependencies = new SourceDependencySyntaxVisitor(new HashSet(gameProjectCompilation.SyntaxTrees), semanticModel).DefaultVisit(syntaxRoot); @@ -106,7 +106,7 @@ public async Task Recompile(Project gameProject, LoggerResult logg for (int i = 0; i < 1000; i++) internalsVisibleToBuilder.AppendFormat(@"[assembly: InternalsVisibleTo(""{0}.Part{1}"")]", gameProject.AssemblyName, i); - var internalsVisibleToSource = CSharpSyntaxTree.ParseText(internalsVisibleToBuilder.ToString(), null, "", Encoding.UTF8).GetText(); + var internalsVisibleToSource = await CSharpSyntaxTree.ParseText(internalsVisibleToBuilder.ToString(), null, "", Encoding.UTF8).GetTextAsync(); // 2. Compile assemblies foreach (var sourceGroup in sortedConnectedGroups.Reverse()) @@ -125,7 +125,7 @@ public async Task Recompile(Project gameProject, LoggerResult logg // Add sources foreach (var syntaxTree in sourceGroup.Vertices) { - project = project.AddDocument(syntaxTree.FilePath, syntaxTree.GetText()).Project; + project = project.AddDocument(syntaxTree.FilePath, await syntaxTree.GetTextAsync()).Project; } // Add references to other sources diff --git a/sources/engine/Stride.Assets.Models/ThreeDAssetImporter.cs b/sources/engine/Stride.Assets.Models/ThreeDAssetImporter.cs index f7d9b2f1d8..5093bb1d77 100644 --- a/sources/engine/Stride.Assets.Models/ThreeDAssetImporter.cs +++ b/sources/engine/Stride.Assets.Models/ThreeDAssetImporter.cs @@ -33,7 +33,7 @@ public override EntityInfo GetEntityInfo(UFile localPath, Logger logger, AssetIm if (!importParameters.InputParameters.TryGet(DeduplicateMaterialsKey, out var deduplicateMaterials)) deduplicateMaterials = true; // Dedupe is the default value - var entityInfo = meshConverter.ExtractEntity(localPath.FullPath, null, importParameters.IsTypeSelectedForOutput(typeof(TextureAsset)), deduplicateMaterials); + var entityInfo = meshConverter.ExtractEntity(localPath.FullPath, null, importParameters.IsTypeSelectedForOutput(), deduplicateMaterials); return entityInfo; } diff --git a/sources/engine/Stride.Assets/AssetCompilerContextExtensions.cs b/sources/engine/Stride.Assets/AssetCompilerContextExtensions.cs index 57bb399dd1..32e2e90edb 100644 --- a/sources/engine/Stride.Assets/AssetCompilerContextExtensions.cs +++ b/sources/engine/Stride.Assets/AssetCompilerContextExtensions.cs @@ -34,7 +34,7 @@ public static GraphicsPlatform GetGraphicsPlatform(this AssetCompilerContext con // If we have a command line override, use it first string graphicsApi; if (context.OptionProperties.TryGetValue("StrideGraphicsApi", out graphicsApi)) - return (GraphicsPlatform)Enum.Parse(typeof(GraphicsPlatform), graphicsApi); + return Enum.Parse(graphicsApi); // Ohterwise, use default as fallback return context.Platform.GetDefaultGraphicsPlatform(); diff --git a/sources/engine/Stride.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Stride.Assets/Navigation/NavigationMeshAssetCompiler.cs index ee72ebe622..de181606ce 100644 --- a/sources/engine/Stride.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Stride.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -331,7 +331,7 @@ private void EnsureClonedSceneAndHash() object loadedHeightfieldInitialData; if (!loadedHeightfieldInitialDatas.TryGetValue(assetReference.Url, out loadedHeightfieldInitialData)) { - loadedHeightfieldInitialData = contentManager.Load(typeof(Heightmap), assetReference.Url); + loadedHeightfieldInitialData = contentManager.Load(assetReference.Url); loadedHeightfieldInitialDatas.Add(assetReference.Url, loadedHeightfieldInitialData); } heightmapSource.Heightmap = loadedHeightfieldInitialData as Heightmap; diff --git a/sources/engine/Stride.Assets/Textures/Packing/TexturePacker.cs b/sources/engine/Stride.Assets/Textures/Packing/TexturePacker.cs index 260bae259e..8dc62d8718 100644 --- a/sources/engine/Stride.Assets/Textures/Packing/TexturePacker.cs +++ b/sources/engine/Stride.Assets/Textures/Packing/TexturePacker.cs @@ -88,7 +88,7 @@ public bool PackTextures(List textureElements) results[bestAlgorithm] = new List(atlasTextureLayouts); - foreach (var heuristicMethod in (TexturePackingMethod[])Enum.GetValues(typeof(TexturePackingMethod))) + foreach (var heuristicMethod in Enum.GetValues()) { if (heuristicMethod == TexturePackingMethod.Best || heuristicMethod == TexturePackingMethod.BestShortSideFit) continue; diff --git a/sources/engine/Stride.Audio/CompressedSoundSource.cs b/sources/engine/Stride.Audio/CompressedSoundSource.cs index f46509ada2..85489709cd 100644 --- a/sources/engine/Stride.Audio/CompressedSoundSource.cs +++ b/sources/engine/Stride.Audio/CompressedSoundSource.cs @@ -260,7 +260,7 @@ protected override unsafe void ExtractAndFillData() //read one packet, size first, then data var len = reader.ReadInt16(); - compressedSoundStream.Read(compressedBuffer, 0, len); + compressedSoundStream.ReadExactly(compressedBuffer, 0, len); currentPacketIndex++; var writePtr = bufferPtr + offset; diff --git a/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics.Tests/BepuTests.cs b/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics.Tests/BepuTests.cs index d17dea04ee..c9e83a8272 100644 --- a/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics.Tests/BepuTests.cs +++ b/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics.Tests/BepuTests.cs @@ -293,7 +293,7 @@ public void ContactImpulseTest() while (contactE.Exit == false) await simulation.AfterUpdate(); - Assert.NotEmpty(contactE.ImpactForces.Where(x => x.Length() > 100)); + Assert.Contains(contactE.ImpactForces, x => x.Length() > 100); game.Exit(); }); diff --git a/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics/Systems/ShapeCacheSystem.cs b/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics/Systems/ShapeCacheSystem.cs index 64832cef95..6a7339e79f 100644 --- a/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics/Systems/ShapeCacheSystem.cs +++ b/sources/engine/Stride.BepuPhysics/Stride.BepuPhysics/Systems/ShapeCacheSystem.cs @@ -226,10 +226,6 @@ internal static Vector3 GetClosestToDecomposableScale(Matrix matrix) static void Orthogonalize(ReadOnlySpan source, Span destination) { // Dump of strides' method to strip the memory alloc, refer to Vector3.Orthogonalize - if (source == null) - throw new ArgumentNullException(nameof(source)); - if (destination == null) - throw new ArgumentNullException(nameof(destination)); if (destination.Length < source.Length) throw new ArgumentOutOfRangeException(nameof(destination), "The destination array must be of same length or larger length than the source array."); diff --git a/sources/engine/Stride.Engine/Rendering/Compositing/VRRendererSettings.cs b/sources/engine/Stride.Engine/Rendering/Compositing/VRRendererSettings.cs index 65584881ee..21fd015f7c 100644 --- a/sources/engine/Stride.Engine/Rendering/Compositing/VRRendererSettings.cs +++ b/sources/engine/Stride.Engine/Rendering/Compositing/VRRendererSettings.cs @@ -26,7 +26,6 @@ public class VRRendererSettings [DefaultValue(false)] public bool IgnoreDevicePosition { get; set; } = false; - private bool _copyMirror = true; /// /// Specifies if VR rendering should be copied to the current render target. /// diff --git a/sources/engine/Stride.Engine/Shaders.Compiler/Internals/NetworkVirtualFileProvider.cs b/sources/engine/Stride.Engine/Shaders.Compiler/Internals/NetworkVirtualFileProvider.cs index a7459cf78f..83dd85b6f2 100644 --- a/sources/engine/Stride.Engine/Shaders.Compiler/Internals/NetworkVirtualFileProvider.cs +++ b/sources/engine/Stride.Engine/Shaders.Compiler/Internals/NetworkVirtualFileProvider.cs @@ -57,7 +57,7 @@ public static void RegisterServer(SocketMessageLayer socketMessageLayer) { var stream = await VirtualFileSystem.OpenStreamAsync(packet.Url, VirtualFileMode.Open, VirtualFileAccess.Read); var data = new byte[stream.Length]; - await stream.ReadAsync(data, 0, data.Length); + await stream.ReadExactlyAsync(data, 0, data.Length); stream.Dispose(); socketMessageLayer.Send(new DownloadFileAnswer { StreamId = packet.StreamId, Data = data }); }); diff --git a/sources/engine/Stride.Graphics.Tests/TestImage.cs b/sources/engine/Stride.Graphics.Tests/TestImage.cs index b1d84b3771..0eac2765b3 100644 --- a/sources/engine/Stride.Graphics.Tests/TestImage.cs +++ b/sources/engine/Stride.Graphics.Tests/TestImage.cs @@ -183,9 +183,9 @@ public void TestPerfLoadSave() [Fact] public void TestLoadAndSave() { - foreach (ImageFileType sourceFormat in Enum.GetValues(typeof(ImageFileType))) + foreach (ImageFileType sourceFormat in Enum.GetValues()) { - foreach (ImageFileType intermediateFormat in Enum.GetValues(typeof(ImageFileType))) + foreach (ImageFileType intermediateFormat in Enum.GetValues()) { if (sourceFormat == ImageFileType.Wmp) // no input image of this format. continue; @@ -230,7 +230,7 @@ public void TestLoadPremultiplied() { var bufferSize = inStream.Length; buffer = new byte[bufferSize]; - inStream.Read(buffer, 0, (int)bufferSize); + inStream.ReadExactly(buffer, 0, (int)bufferSize); } using (image = Image.Load(buffer)) @@ -271,7 +271,7 @@ private void ProcessFiles(Game game, ImageFileType sourceFormat, ImageFileType i { var bufferSize = inStream.Length; buffer = new byte[bufferSize]; - inStream.Read(buffer, 0, (int)bufferSize); + inStream.ReadExactly(buffer, 0, (int)bufferSize); } using (image = Image.Load(buffer)) diff --git a/sources/engine/Stride.Graphics/Font/FontManager.cs b/sources/engine/Stride.Graphics/Font/FontManager.cs index cac5ae1ab5..791bce6201 100644 --- a/sources/engine/Stride.Graphics/Font/FontManager.cs +++ b/sources/engine/Stride.Graphics/Font/FontManager.cs @@ -314,7 +314,7 @@ private void LoadFontInMemory(string fontPath) { // create the font data from the stream var newFontData = new byte[fontStream.Length]; - fontStream.Read(newFontData, 0, newFontData.Length); + fontStream.ReadExactly(newFontData); lock (freetypeLibrary) cachedFontFaces[fontPath] = freetypeLibrary.NewMemoryFace(newFontData, 0); diff --git a/sources/engine/Stride.Input.Tests/SensorGameTest.cs b/sources/engine/Stride.Input.Tests/SensorGameTest.cs index 60ce2548c3..a4cbb0262e 100644 --- a/sources/engine/Stride.Input.Tests/SensorGameTest.cs +++ b/sources/engine/Stride.Input.Tests/SensorGameTest.cs @@ -133,7 +133,7 @@ private void BuildUI() private void ChangeScene(int i) { - var sceneCount = Enum.GetNames(typeof(DebugScenes)).Length; + var sceneCount = Enum.GetNames().Length; currentScene = (DebugScenes)((i + (int)currentScene + sceneCount) % sceneCount); currentText.Text = currentScene.ToString(); diff --git a/sources/engine/Stride.Input.Tests/TestInput.cs b/sources/engine/Stride.Input.Tests/TestInput.cs index 8c1dfbb409..867bb56e85 100644 --- a/sources/engine/Stride.Input.Tests/TestInput.cs +++ b/sources/engine/Stride.Input.Tests/TestInput.cs @@ -27,12 +27,12 @@ void TestPressRelease() Input.Update(DrawTime); // Test press - Assert.Equal(1, events.Count); + Assert.Single(events); Assert.True(events[0] is KeyEvent); var keyEvent = (KeyEvent)events[0]; - Assert.True(keyEvent.Key == Keys.A); + Assert.Equal(Keys.A, keyEvent.Key); Assert.True(keyEvent.IsDown); - Assert.True(keyEvent.RepeatCount == 0); + Assert.Equal(0, keyEvent.RepeatCount); Assert.True(keyEvent.Device == keyboard); // Check pressed/released states @@ -44,11 +44,11 @@ void TestPressRelease() Input.Update(DrawTime); // Test release - Assert.Equal(1, events.Count); + Assert.Single(events); Assert.True(events[0] is KeyEvent); keyEvent = (KeyEvent)events[0]; - Assert.True(keyEvent.Key == Keys.A); - Assert.True(!keyEvent.IsDown); + Assert.Equal(Keys.A, keyEvent.Key); + Assert.False(keyEvent.IsDown); // Check pressed/released states Assert.False(keyboard.IsKeyPressed(Keys.A)); @@ -74,12 +74,12 @@ void TestRepeat() Input.Update(DrawTime); // Test press with release - Assert.Equal(1, events.Count); + Assert.Single(events); Assert.True(events[0] is KeyEvent); var keyEvent = (KeyEvent)events[0]; - Assert.True(keyEvent.Key == Keys.A); + Assert.Equal(Keys.A, keyEvent.Key); Assert.True(keyEvent.IsDown); - Assert.True(keyEvent.RepeatCount == 3); + Assert.Equal(3, keyEvent.RepeatCount); Assert.True(keyEvent.Device == keyboard); // Check pressed/released states (Pressed events should still be sent when repeating) @@ -91,11 +91,11 @@ void TestRepeat() Input.Update(DrawTime); // Test release - Assert.Equal(1, events.Count); + Assert.Single(events); Assert.True(events[0] is KeyEvent); keyEvent = (KeyEvent)events[0]; - Assert.True(keyEvent.Key == Keys.A); - Assert.True(!keyEvent.IsDown); + Assert.Equal(Keys.A, keyEvent.Key); + Assert.False(keyEvent.IsDown); } /// @@ -129,9 +129,9 @@ void TestMouse() Assert.False(mouse.IsButtonReleased(MouseButton.Left)); Assert.True(mouse.IsButtonDown(MouseButton.Left)); - Assert.Equal(1, mouse.PressedPointers.Count); - Assert.Equal(0, mouse.ReleasedPointers.Count); - Assert.Equal(1, mouse.DownPointers.Count); + Assert.Single(mouse.PressedPointers); + Assert.Empty(mouse.ReleasedPointers); + Assert.Single(mouse.DownPointers); // Check delta Assert.Equal(new Vector2(0.1f, 0.0f), Input.PointerEvents[0].DeltaPosition); @@ -147,7 +147,7 @@ void TestMouse() Input.Update(DrawTime); // Check up - Assert.Equal(1, Input.PointerEvents.Count); + Assert.Single(Input.PointerEvents); Assert.Equal(PointerEventType.Released, Input.PointerEvents[0].EventType); Assert.False(Input.PointerEvents[0].IsDown); @@ -156,9 +156,9 @@ void TestMouse() Assert.True(mouse.IsButtonReleased(MouseButton.Left)); Assert.False(mouse.IsButtonDown(MouseButton.Left)); - Assert.Equal(0, mouse.PressedPointers.Count); - Assert.Equal(1, mouse.ReleasedPointers.Count); - Assert.Equal(0, mouse.DownPointers.Count); + Assert.Empty(mouse.PressedPointers); + Assert.Single(mouse.ReleasedPointers); + Assert.Empty(mouse.DownPointers); } /// @@ -289,7 +289,7 @@ void TestLockedMousePosition() /// void TestGamePad() { - Assert.Equal(0, InputSourceSimulated.GamePads.Count); + Assert.Empty(InputSourceSimulated.GamePads); Assert.False(Input.HasGamePad); Assert.Null(Input.DefaultGamePad); diff --git a/sources/engine/Stride.Physics.Tests/ColliderShapesTest.cs b/sources/engine/Stride.Physics.Tests/ColliderShapesTest.cs index 8a6f482903..4da2dd548e 100644 --- a/sources/engine/Stride.Physics.Tests/ColliderShapesTest.cs +++ b/sources/engine/Stride.Physics.Tests/ColliderShapesTest.cs @@ -280,7 +280,7 @@ public void VerifyColliderShapeSetup() //add collider shape body.ColliderShape = new SphereColliderShape(false, 1.0f); //check if proper colliderShape setup took place - Assert.True(body.ColliderShape != null); + Assert.NotNull(body.ColliderShape); Assert.Equal(ColliderShapeTypes.Sphere, body.ColliderShape.Type); Assert.Equal(RigidBodyTypes.Dynamic, body.RigidBodyType); diff --git a/sources/engine/Stride.Physics/Engine/PhysicsShapesRenderingService.cs b/sources/engine/Stride.Physics/Engine/PhysicsShapesRenderingService.cs index 265d54e7fd..fa9adc0de9 100644 --- a/sources/engine/Stride.Physics/Engine/PhysicsShapesRenderingService.cs +++ b/sources/engine/Stride.Physics/Engine/PhysicsShapesRenderingService.cs @@ -48,7 +48,7 @@ public override void Initialize() { graphicsDevice = Services.GetSafeServiceAs().GraphicsDevice; - foreach (var typeObject in Enum.GetValues(typeof(ComponentType))) + foreach (var typeObject in Enum.GetValues()) { var type = (ComponentType)typeObject; componentTypeDefaultMaterial[type] = PhysicsDebugShapeMaterial.CreateDefault(graphicsDevice, Color.AdjustSaturation(componentTypeColor[type], 0.77f), 1); diff --git a/sources/engine/Stride.Rendering/Rendering/Materials/MaterialBlendLayerContext.cs b/sources/engine/Stride.Rendering/Rendering/Materials/MaterialBlendLayerContext.cs index 235254e2d0..7f554dbace 100644 --- a/sources/engine/Stride.Rendering/Rendering/Materials/MaterialBlendLayerContext.cs +++ b/sources/engine/Stride.Rendering/Rendering/Materials/MaterialBlendLayerContext.cs @@ -32,7 +32,7 @@ public MaterialBlendLayerContext(MaterialGeneratorContext context, MaterialBlend ShadingModels = new MaterialShadingModelCollection(); ContextPerStage = new Dictionary(); - foreach (MaterialShaderStage stage in Enum.GetValues(typeof(MaterialShaderStage))) + foreach (MaterialShaderStage stage in Enum.GetValues()) { ContextPerStage[stage] = new MaterialBlendLayerPerStageContext(); } diff --git a/sources/engine/Stride.Rendering/Rendering/Materials/MaterialGeneratorContext.cs b/sources/engine/Stride.Rendering/Rendering/Materials/MaterialGeneratorContext.cs index 71f7fee8d7..a4f97abf12 100644 --- a/sources/engine/Stride.Rendering/Rendering/Materials/MaterialGeneratorContext.cs +++ b/sources/engine/Stride.Rendering/Rendering/Materials/MaterialGeneratorContext.cs @@ -53,7 +53,7 @@ public MaterialGeneratorContext(Material material = null, GraphicsDevice graphic { this.Material = material ?? new Material(); - foreach (MaterialShaderStage stage in Enum.GetValues(typeof(MaterialShaderStage))) + foreach (MaterialShaderStage stage in Enum.GetValues()) { finalCallbacks[stage] = new List<(int, MaterialGeneratorCallback)>(); } @@ -403,7 +403,7 @@ private void ProcessIntermediateLayer(MaterialBlendLayerContext layer, bool isLa // -------------------------------------------- // Copy streams to parent, but not for the PixelLayer if SM is changing // -------------------------------------------- - foreach (MaterialShaderStage stage in Enum.GetValues(typeof(MaterialShaderStage))) + foreach (MaterialShaderStage stage in Enum.GetValues()) { var stageContext = layer.GetContextPerStage(stage); var parentStageContext = parent.GetContextPerStage(stage); @@ -578,7 +578,7 @@ private void ProcessRootLayer(MaterialBlendLayerContext layer) private void BlendStreams(MaterialBlendLayerContext layer) { // Generate Vertex and Pixel surface shaders - foreach (MaterialShaderStage stage in Enum.GetValues(typeof(MaterialShaderStage))) + foreach (MaterialShaderStage stage in Enum.GetValues()) { // If we don't have any stream set, we have nothing to blend var stageContext = layer.GetContextPerStage(stage); diff --git a/sources/engine/Stride.Shaders.Parser/Mixins/ShaderSourceManager.cs b/sources/engine/Stride.Shaders.Parser/Mixins/ShaderSourceManager.cs index d922be2387..d18330e02d 100644 --- a/sources/engine/Stride.Shaders.Parser/Mixins/ShaderSourceManager.cs +++ b/sources/engine/Stride.Shaders.Parser/Mixins/ShaderSourceManager.cs @@ -194,7 +194,7 @@ public ShaderSourceWithHash LoadShaderSource(string type, string shaderSourceCod { sourceStream.Position = 0; var data = new byte[sourceStream.Length]; - sourceStream.Read(data, 0, (int)sourceStream.Length); + sourceStream.ReadExactly(data, 0, (int)sourceStream.Length); shaderSource.Hash = ObjectId.FromBytes(data); } else diff --git a/sources/engine/Stride.VirtualReality/OpenVR/openvr_api.cs b/sources/engine/Stride.VirtualReality/OpenVR/openvr_api.cs index 178724e9d5..d743e594e7 100644 --- a/sources/engine/Stride.VirtualReality/OpenVR/openvr_api.cs +++ b/sources/engine/Stride.VirtualReality/OpenVR/openvr_api.cs @@ -2018,7 +2018,7 @@ public class CVRSystem IVRSystem FnTable; internal CVRSystem(IntPtr pInterface) { - FnTable = (IVRSystem)Marshal.PtrToStructure(pInterface, typeof(IVRSystem)); + FnTable = Marshal.PtrToStructure(pInterface); } public void GetRecommendedRenderTargetSize(ref uint pnWidth,ref uint pnHeight) { @@ -2191,7 +2191,7 @@ public bool PollNextEvent(ref VREvent_t pEvent,uint uncbVREvent) VREvent_t_Packed event_packed = new VREvent_t_Packed(); u.pPollNextEventPacked = null; u.pPollNextEvent = FnTable.PollNextEvent; - bool packed_result = u.pPollNextEventPacked(ref event_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t_Packed))); + bool packed_result = u.pPollNextEventPacked(ref event_packed,(uint)Marshal.SizeOf()); event_packed.Unpack(ref pEvent); return packed_result; @@ -2237,7 +2237,7 @@ public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerStat VRControllerState_t_Packed state_packed = new VRControllerState_t_Packed(pControllerState); u.pGetControllerStatePacked = null; u.pGetControllerState = FnTable.GetControllerState; - bool packed_result = u.pGetControllerStatePacked(unControllerDeviceIndex,ref state_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t_Packed))); + bool packed_result = u.pGetControllerStatePacked(unControllerDeviceIndex,ref state_packed,(uint)Marshal.SizeOf()); state_packed.Unpack(ref pControllerState); return packed_result; @@ -2268,7 +2268,7 @@ public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unCo VRControllerState_t_Packed state_packed = new VRControllerState_t_Packed(pControllerState); u.pGetControllerStateWithPosePacked = null; u.pGetControllerStateWithPose = FnTable.GetControllerStateWithPose; - bool packed_result = u.pGetControllerStateWithPosePacked(eOrigin,unControllerDeviceIndex,ref state_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t_Packed)),ref pTrackedDevicePose); + bool packed_result = u.pGetControllerStateWithPosePacked(eOrigin,unControllerDeviceIndex,ref state_packed,(uint)Marshal.SizeOf(), ref pTrackedDevicePose); state_packed.Unpack(ref pControllerState); return packed_result; @@ -2338,7 +2338,7 @@ public class CVRExtendedDisplay IVRExtendedDisplay FnTable; internal CVRExtendedDisplay(IntPtr pInterface) { - FnTable = (IVRExtendedDisplay)Marshal.PtrToStructure(pInterface, typeof(IVRExtendedDisplay)); + FnTable = Marshal.PtrToStructure(pInterface); } public void GetWindowBounds(ref int pnX,ref int pnY,ref uint pnWidth,ref uint pnHeight) { @@ -2370,7 +2370,7 @@ public class CVRTrackedCamera IVRTrackedCamera FnTable; internal CVRTrackedCamera(IntPtr pInterface) { - FnTable = (IVRTrackedCamera)Marshal.PtrToStructure(pInterface, typeof(IVRTrackedCamera)); + FnTable = Marshal.PtrToStructure(pInterface); } public string GetCameraErrorNameFromEnum(EVRTrackedCameraError eCameraError) { @@ -2457,7 +2457,7 @@ public class CVRApplications IVRApplications FnTable; internal CVRApplications(IntPtr pInterface) { - FnTable = (IVRApplications)Marshal.PtrToStructure(pInterface, typeof(IVRApplications)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRApplicationError AddApplicationManifest(string pchApplicationManifestFullPath,bool bTemporary) { @@ -2669,7 +2669,7 @@ public class CVRChaperone IVRChaperone FnTable; internal CVRChaperone(IntPtr pInterface) { - FnTable = (IVRChaperone)Marshal.PtrToStructure(pInterface, typeof(IVRChaperone)); + FnTable = Marshal.PtrToStructure(pInterface); } public ChaperoneCalibrationState GetCalibrationState() { @@ -2721,7 +2721,7 @@ public class CVRChaperoneSetup IVRChaperoneSetup FnTable; internal CVRChaperoneSetup(IntPtr pInterface) { - FnTable = (IVRChaperoneSetup)Marshal.PtrToStructure(pInterface, typeof(IVRChaperoneSetup)); + FnTable = Marshal.PtrToStructure(pInterface); } public bool CommitWorkingCopy(EChaperoneConfigFile configFile) { @@ -2832,7 +2832,7 @@ public class CVRCompositor IVRCompositor FnTable; internal CVRCompositor(IntPtr pInterface) { - FnTable = (IVRCompositor)Marshal.PtrToStructure(pInterface, typeof(IVRCompositor)); + FnTable = Marshal.PtrToStructure(pInterface); } public void SetTrackingSpace(ETrackingUniverseOrigin eOrigin) { @@ -3081,7 +3081,7 @@ public class CVROverlay IVROverlay FnTable; internal CVROverlay(IntPtr pInterface) { - FnTable = (IVROverlay)Marshal.PtrToStructure(pInterface, typeof(IVROverlay)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVROverlayError FindOverlay(string pchOverlayKey,ref ulong pOverlayHandle) { @@ -3352,7 +3352,7 @@ public bool PollNextOverlayEvent(ulong ulOverlayHandle,ref VREvent_t pEvent,uint VREvent_t_Packed event_packed = new VREvent_t_Packed(); u.pPollNextOverlayEventPacked = null; u.pPollNextOverlayEvent = FnTable.PollNextOverlayEvent; - bool packed_result = u.pPollNextOverlayEventPacked(ulOverlayHandle,ref event_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t_Packed))); + bool packed_result = u.pPollNextOverlayEventPacked(ulOverlayHandle,ref event_packed,(uint)Marshal.SizeOf()); event_packed.Unpack(ref pEvent); return packed_result; @@ -3565,7 +3565,7 @@ public class CVROverlayView IVROverlayView FnTable; internal CVROverlayView(IntPtr pInterface) { - FnTable = (IVROverlayView)Marshal.PtrToStructure(pInterface, typeof(IVROverlayView)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVROverlayError AcquireOverlayView(ulong ulOverlayHandle,ref VRNativeDevice_t pNativeDevice,ref VROverlayView_t pOverlayView,uint unOverlayViewSize) { @@ -3594,7 +3594,7 @@ public class CVRHeadsetView IVRHeadsetView FnTable; internal CVRHeadsetView(IntPtr pInterface) { - FnTable = (IVRHeadsetView)Marshal.PtrToStructure(pInterface, typeof(IVRHeadsetView)); + FnTable = Marshal.PtrToStructure(pInterface); } public void SetHeadsetViewSize(uint nWidth,uint nHeight) { @@ -3647,7 +3647,7 @@ public class CVRRenderModels IVRRenderModels FnTable; internal CVRRenderModels(IntPtr pInterface) { - FnTable = (IVRRenderModels)Marshal.PtrToStructure(pInterface, typeof(IVRRenderModels)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRRenderModelError LoadRenderModel_Async(string pchRenderModelName,ref IntPtr ppRenderModel) { @@ -3805,7 +3805,7 @@ public class CVRNotifications IVRNotifications FnTable; internal CVRNotifications(IntPtr pInterface) { - FnTable = (IVRNotifications)Marshal.PtrToStructure(pInterface, typeof(IVRNotifications)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRNotificationError CreateNotification(ulong ulOverlayHandle,ulong ulUserValue,EVRNotificationType type,string pchText,EVRNotificationStyle style,ref NotificationBitmap_t pImage,ref uint pNotificationId) { @@ -3828,7 +3828,7 @@ public class CVRSettings IVRSettings FnTable; internal CVRSettings(IntPtr pInterface) { - FnTable = (IVRSettings)Marshal.PtrToStructure(pInterface, typeof(IVRSettings)); + FnTable = Marshal.PtrToStructure(pInterface); } public string GetSettingsErrorNameFromEnum(EVRSettingsError eError) { @@ -3926,7 +3926,7 @@ public class CVRScreenshots IVRScreenshots FnTable; internal CVRScreenshots(IntPtr pInterface) { - FnTable = (IVRScreenshots)Marshal.PtrToStructure(pInterface, typeof(IVRScreenshots)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRScreenshotError RequestScreenshot(ref uint pOutScreenshotHandle,EVRScreenshotType type,string pchPreviewFilename,string pchVRFilename) { @@ -3985,7 +3985,7 @@ public class CVRResources IVRResources FnTable; internal CVRResources(IntPtr pInterface) { - FnTable = (IVRResources)Marshal.PtrToStructure(pInterface, typeof(IVRResources)); + FnTable = Marshal.PtrToStructure(pInterface); } public uint LoadSharedResource(string pchResourceName,string pchBuffer,uint unBufferLen) { @@ -4011,7 +4011,7 @@ public class CVRDriverManager IVRDriverManager FnTable; internal CVRDriverManager(IntPtr pInterface) { - FnTable = (IVRDriverManager)Marshal.PtrToStructure(pInterface, typeof(IVRDriverManager)); + FnTable = Marshal.PtrToStructure(pInterface); } public uint GetDriverCount() { @@ -4043,7 +4043,7 @@ public class CVRInput IVRInput FnTable; internal CVRInput(IntPtr pInterface) { - FnTable = (IVRInput)Marshal.PtrToStructure(pInterface, typeof(IVRInput)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRInputError SetActionManifestPath(string pchActionManifestPath) { @@ -4233,7 +4233,7 @@ public class CVRIOBuffer IVRIOBuffer FnTable; internal CVRIOBuffer(IntPtr pInterface) { - FnTable = (IVRIOBuffer)Marshal.PtrToStructure(pInterface, typeof(IVRIOBuffer)); + FnTable = Marshal.PtrToStructure(pInterface); } public EIOBufferError Open(string pchPath,EIOBufferMode mode,uint unElementSize,uint unElements,ref ulong pulBuffer) { @@ -4277,7 +4277,7 @@ public class CVRSpatialAnchors IVRSpatialAnchors FnTable; internal CVRSpatialAnchors(IntPtr pInterface) { - FnTable = (IVRSpatialAnchors)Marshal.PtrToStructure(pInterface, typeof(IVRSpatialAnchors)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRSpatialAnchorError CreateSpatialAnchorFromDescriptor(string pchDescriptor,ref uint pHandleOut) { @@ -4312,7 +4312,7 @@ public class CVRDebug IVRDebug FnTable; internal CVRDebug(IntPtr pInterface) { - FnTable = (IVRDebug)Marshal.PtrToStructure(pInterface, typeof(IVRDebug)); + FnTable = Marshal.PtrToStructure(pInterface); } public EVRDebugError EmitVrProfilerEvent(string pchMessage) { @@ -4349,7 +4349,7 @@ public class CVRProperties IVRProperties FnTable; internal CVRProperties(IntPtr pInterface) { - FnTable = (IVRProperties)Marshal.PtrToStructure(pInterface, typeof(IVRProperties)); + FnTable = Marshal.PtrToStructure(pInterface); } public ETrackedPropertyError ReadPropertyBatch(ulong ulContainerHandle,ref PropertyRead_t pBatch,uint unBatchEntryCount) { @@ -4379,7 +4379,7 @@ public class CVRPaths IVRPaths FnTable; internal CVRPaths(IntPtr pInterface) { - FnTable = (IVRPaths)Marshal.PtrToStructure(pInterface, typeof(IVRPaths)); + FnTable = Marshal.PtrToStructure(pInterface); } public ETrackedPropertyError ReadPathBatch(ulong ulRootHandle,ref PathRead_t pBatch,uint unBatchEntryCount) { @@ -4413,7 +4413,7 @@ public class CVRBlockQueue IVRBlockQueue FnTable; internal CVRBlockQueue(IntPtr pInterface) { - FnTable = (IVRBlockQueue)Marshal.PtrToStructure(pInterface, typeof(IVRBlockQueue)); + FnTable = Marshal.PtrToStructure(pInterface); } public EBlockQueueError Create(ref ulong pulQueueHandle,string pchPath,uint unBlockDataSize,uint unBlockHeaderSize,uint unBlockCount) { diff --git a/sources/presentation/Stride.Core.Presentation.Tests/TestObservableList.cs b/sources/presentation/Stride.Core.Presentation.Tests/TestObservableList.cs index bae0272d78..3eeb583ba4 100644 --- a/sources/presentation/Stride.Core.Presentation.Tests/TestObservableList.cs +++ b/sources/presentation/Stride.Core.Presentation.Tests/TestObservableList.cs @@ -49,7 +49,7 @@ public void TestAdd() Assert.Equal(NotifyCollectionChangedAction.Add, e.Action); Assert.Equal(3, e.NewStartingIndex); Assert.NotNull(e.NewItems); - Assert.Equal(1, e.NewItems.Count); + Assert.Single(e.NewItems); Assert.Equal("ddd", e.NewItems[0]); collectionChangedInvoked = true; }; @@ -149,7 +149,7 @@ public void TestRemove() Assert.Equal(NotifyCollectionChangedAction.Remove, e.Action); Assert.Equal(1, e.OldStartingIndex); Assert.NotNull(e.OldItems); - Assert.Equal(1, e.OldItems.Count); + Assert.Single(e.OldItems); Assert.Equal("bbb", e.OldItems[0]); collectionChangedInvoked = true; }; @@ -195,7 +195,7 @@ public void TestInsert() Assert.Equal(NotifyCollectionChangedAction.Add, e.Action); Assert.Equal(1, e.NewStartingIndex); Assert.NotNull(e.NewItems); - Assert.Equal(1, e.NewItems.Count); + Assert.Single(e.NewItems); Assert.Equal("ddd", e.NewItems[0]); collectionChangedInvoked = true; }; @@ -227,7 +227,7 @@ public void TestRemoveAt() Assert.Equal(NotifyCollectionChangedAction.Remove, e.Action); Assert.Equal(1, e.OldStartingIndex); Assert.NotNull(e.OldItems); - Assert.Equal(1, e.OldItems.Count); + Assert.Single(e.OldItems); Assert.Equal("bbb", e.OldItems[0]); collectionChangedInvoked = true; }; diff --git a/sources/presentation/Stride.Core.Presentation.Tests/TestObservableSet.cs b/sources/presentation/Stride.Core.Presentation.Tests/TestObservableSet.cs index 967704e1c8..6f371608d5 100644 --- a/sources/presentation/Stride.Core.Presentation.Tests/TestObservableSet.cs +++ b/sources/presentation/Stride.Core.Presentation.Tests/TestObservableSet.cs @@ -72,7 +72,7 @@ public void TestAdd() Assert.Equal(NotifyCollectionChangedAction.Add, e.Action); Assert.Equal(3, e.NewStartingIndex); Assert.NotNull(e.NewItems); - Assert.Equal(1, e.NewItems.Count); + Assert.Single(e.NewItems); Assert.Equal("ddd", e.NewItems[0]); collectionChangedInvoked = true; }; @@ -172,7 +172,7 @@ public void TestRemove() Assert.Equal(NotifyCollectionChangedAction.Remove, e.Action); Assert.Equal(1, e.OldStartingIndex); Assert.NotNull(e.OldItems); - Assert.Equal(1, e.OldItems.Count); + Assert.Single(e.OldItems); Assert.Equal("bbb", e.OldItems[0]); collectionChangedInvoked = true; }; @@ -218,7 +218,7 @@ public void TestInsert() Assert.Equal(NotifyCollectionChangedAction.Add, e.Action); Assert.Equal(1, e.NewStartingIndex); Assert.NotNull(e.NewItems); - Assert.Equal(1, e.NewItems.Count); + Assert.Single(e.NewItems); Assert.Equal("ddd", e.NewItems[0]); collectionChangedInvoked = true; }; @@ -250,7 +250,7 @@ public void TestRemoveAt() Assert.Equal(NotifyCollectionChangedAction.Remove, e.Action); Assert.Equal(1, e.OldStartingIndex); Assert.NotNull(e.OldItems); - Assert.Equal(1, e.OldItems.Count); + Assert.Single(e.OldItems); Assert.Equal("bbb", e.OldItems[0]); collectionChangedInvoked = true; }; diff --git a/sources/presentation/Stride.Core.Presentation.Tests/TestWindowsManager.cs b/sources/presentation/Stride.Core.Presentation.Tests/TestWindowsManager.cs index d361a065f9..54442a0728 100644 --- a/sources/presentation/Stride.Core.Presentation.Tests/TestWindowsManager.cs +++ b/sources/presentation/Stride.Core.Presentation.Tests/TestWindowsManager.cs @@ -186,7 +186,7 @@ private void AssertStep(Step step, Window mainWindow, Window modalWindow, Window } if (modalWindow != null) { - Assert.Equal(1, WindowManager.ModalWindows.Count); + Assert.Single(WindowManager.ModalWindows); var winInfo = WindowManager.ModalWindows[0]; Assert.Equal(modalWindow, winInfo.Window); Assert.True(winInfo.IsModal); @@ -194,11 +194,11 @@ private void AssertStep(Step step, Window mainWindow, Window modalWindow, Window } else { - Assert.Equal(0, WindowManager.ModalWindows.Count); + Assert.Empty(WindowManager.ModalWindows); } if (blockingWindow != null) { - Assert.Equal(1, WindowManager.BlockingWindows.Count); + Assert.Single(WindowManager.BlockingWindows); var winInfo = WindowManager.BlockingWindows[0]; Assert.Equal(blockingWindow, winInfo.Window); Assert.False(winInfo.IsModal); @@ -207,7 +207,7 @@ private void AssertStep(Step step, Window mainWindow, Window modalWindow, Window } else { - Assert.Equal(0, WindowManager.BlockingWindows.Count); + Assert.Empty(WindowManager.BlockingWindows); } } } diff --git a/sources/presentation/Stride.Core.Presentation.Wpf/Behaviors/BehaviorProperties.cs b/sources/presentation/Stride.Core.Presentation.Wpf/Behaviors/BehaviorProperties.cs index 1ee90b350a..bd90958f1b 100644 --- a/sources/presentation/Stride.Core.Presentation.Wpf/Behaviors/BehaviorProperties.cs +++ b/sources/presentation/Stride.Core.Presentation.Wpf/Behaviors/BehaviorProperties.cs @@ -131,7 +131,7 @@ private static IntPtr WindowProc([NotNull] Window window, IntPtr hwnd, int msg, if (monitorInfo == null) break; - var mmi = (NativeHelper.MINMAXINFO)Marshal.PtrToStructure(lparam, typeof(NativeHelper.MINMAXINFO)); + var mmi = Marshal.PtrToStructure(lparam); var rcWorkArea = monitorInfo.rcWork; var rcMonitorArea = monitorInfo.rcMonitor; diff --git a/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyExtension.cs b/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyExtension.cs index 47ec19bcc0..2672a5a27d 100644 --- a/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyExtension.cs +++ b/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyExtension.cs @@ -23,7 +23,7 @@ public class KeyExtension : MarkupExtension /// A string representing the key. public KeyExtension([NotNull] string key) { - Key = (Key)Enum.Parse(typeof(Key), key, true); + Key = Enum.Parse(key, true); } /// diff --git a/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyGestureExtension.cs b/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyGestureExtension.cs index 3d1ea6796f..12101851fe 100644 --- a/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyGestureExtension.cs +++ b/sources/presentation/Stride.Core.Presentation.Wpf/MarkupExtensions/KeyGestureExtension.cs @@ -28,10 +28,10 @@ public KeyGestureExtension([NotNull] string gesture) for (int i = 0; i < tokens.Length - 1; ++i) { var token = tokens[i].Replace("Ctrl", "Control"); - var modifier = (ModifierKeys)Enum.Parse(typeof(ModifierKeys), token, true); + var modifier = Enum.Parse(token, true); modifiers |= modifier; } - var key = (Key)Enum.Parse(typeof(Key), tokens[tokens.Length - 1], true); + var key = Enum.Parse(tokens[tokens.Length - 1], true); Gesture = new KeyGesture(key, modifiers); } diff --git a/sources/presentation/Stride.Core.Presentation.Wpf/ValueConverters/EnumToDisplayName.cs b/sources/presentation/Stride.Core.Presentation.Wpf/ValueConverters/EnumToDisplayName.cs index 2080fcdbc7..061380875b 100644 --- a/sources/presentation/Stride.Core.Presentation.Wpf/ValueConverters/EnumToDisplayName.cs +++ b/sources/presentation/Stride.Core.Presentation.Wpf/ValueConverters/EnumToDisplayName.cs @@ -22,7 +22,7 @@ public override object Convert(object value, Type targetType, object parameter, if (memberInfo == null) return stringValue; - var attribute = memberInfo.GetCustomAttribute(typeof(DisplayAttribute), false) as DisplayAttribute; + var attribute = memberInfo.GetCustomAttribute(false) as DisplayAttribute; if (attribute == null) return stringValue; diff --git a/sources/presentation/Stride.Core.Presentation/Extensions/ClassFieldExtensions.cs b/sources/presentation/Stride.Core.Presentation/Extensions/ClassFieldExtensions.cs index 7ba63a0fec..d1ca9541ba 100644 --- a/sources/presentation/Stride.Core.Presentation/Extensions/ClassFieldExtensions.cs +++ b/sources/presentation/Stride.Core.Presentation/Extensions/ClassFieldExtensions.cs @@ -11,7 +11,7 @@ public static Func GetFieldAccessor(string { var instanceParam = Expression.Parameter(typeof(TInstance), "instance"); var member = Expression.Field(instanceParam, fieldName); - var lambda = Expression.Lambda(typeof(Func), member, instanceParam); + var lambda = Expression.Lambda>(member, instanceParam); return (Func)lambda.Compile(); } @@ -20,7 +20,7 @@ public static Func GetFieldAccessor(string fieldName, Type insta { var instanceParam = Expression.Parameter(instanceType, "instance"); var member = Expression.Field(instanceParam, fieldName); - var lambda = Expression.Lambda(typeof(Func), member, instanceParam); + var lambda = Expression.Lambda>(member, instanceParam); return (Func)lambda.Compile(); } @@ -31,7 +31,7 @@ public static Action SetFieldAccessor(stri var valueParam = Expression.Parameter(typeof(TValue), "value"); var member = Expression.Field(instanceParam, fieldName); var assign = Expression.Assign(member, valueParam); - var lambda = Expression.Lambda(typeof(Action), assign, instanceParam, valueParam); + var lambda = Expression.Lambda>(assign, instanceParam, valueParam); return (Action)lambda.Compile(); } @@ -42,7 +42,7 @@ public static Action SetFieldAccessor(string fieldName, Type ins var valueParam = Expression.Parameter(valueType, "value"); var member = Expression.Field(instanceParam, fieldName); var assign = Expression.Assign(member, valueParam); - var lambda = Expression.Lambda(typeof(Action), assign, instanceParam, valueParam); + var lambda = Expression.Lambda>(assign, instanceParam, valueParam); return (Action)lambda.Compile(); } diff --git a/sources/presentation/Stride.Core.Presentation/ViewModels/ViewModelServiceProvider.cs b/sources/presentation/Stride.Core.Presentation/ViewModels/ViewModelServiceProvider.cs index 57fbf62ded..2d01373d99 100644 --- a/sources/presentation/Stride.Core.Presentation/ViewModels/ViewModelServiceProvider.cs +++ b/sources/presentation/Stride.Core.Presentation/ViewModels/ViewModelServiceProvider.cs @@ -105,7 +105,6 @@ public object Get(Type serviceType) /// public T Get() where T : class { - var result = TryGet(typeof(T)) as T; - return result ?? throw new InvalidOperationException("No service matches the given type."); + return TryGet() ?? throw new InvalidOperationException("No service matches the given type."); } } diff --git a/sources/shared/AttachedChildProcessJob.cs b/sources/shared/AttachedChildProcessJob.cs index fbec7da51f..e32ec8df45 100644 --- a/sources/shared/AttachedChildProcessJob.cs +++ b/sources/shared/AttachedChildProcessJob.cs @@ -30,7 +30,7 @@ public AttachedChildProcessJob(Process process) } }; - int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); + int length = Marshal.SizeOf(); var extendedInfoPtr = Marshal.AllocHGlobal(length); Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false); diff --git a/sources/tests/tools/Stride.TextureConverter.Tests/DxtTexLibTest.cs b/sources/tests/tools/Stride.TextureConverter.Tests/DxtTexLibTest.cs index afded1be1e..139fe8aecc 100644 --- a/sources/tests/tools/Stride.TextureConverter.Tests/DxtTexLibTest.cs +++ b/sources/tests/tools/Stride.TextureConverter.Tests/DxtTexLibTest.cs @@ -97,7 +97,7 @@ public void DecompressFailTest(string file) { TexImage image = TestTools.Load(library, file); - Assert.True(image.Format == Stride.Graphics.PixelFormat.B8G8R8A8_UNorm); + Assert.Equal(Stride.Graphics.PixelFormat.B8G8R8A8_UNorm, image.Format); try { diff --git a/sources/tests/tools/Stride.TextureConverter.Tests/TexLibraryTest.cs b/sources/tests/tools/Stride.TextureConverter.Tests/TexLibraryTest.cs index eb7b39f127..6279cfd5ae 100644 --- a/sources/tests/tools/Stride.TextureConverter.Tests/TexLibraryTest.cs +++ b/sources/tests/tools/Stride.TextureConverter.Tests/TexLibraryTest.cs @@ -39,7 +39,7 @@ public static void FactorRescaleTest(TexImage image, ITexLibrary library, Filter library.Execute(image, request); Assert.True(image.Width == width); Assert.True(image.Height == height); - Assert.True(image.MipmapCount == 1); + Assert.Equal(1, image.MipmapCount); image.Update(); @@ -56,7 +56,7 @@ public static void FixedRescaleTest(TexImage image, ITexLibrary library, Filter. library.Execute(image, request); Assert.True(image.Width == width); Assert.True(image.Height == height); - Assert.True(image.MipmapCount == 1); + Assert.Equal(1, image.MipmapCount); image.Update(); @@ -86,24 +86,24 @@ public static void DecompressTest(TexImage image, ITexLibrary library) { Assert.True(image.Format.IsCompressed); library.Execute(image, new DecompressingRequest(false)); - Assert.True(image.Format == PixelFormat.R8G8B8A8_UNorm); + Assert.Equal(PixelFormat.R8G8B8A8_UNorm, image.Format); Assert.Equal(TestTools.GetInstance().Checksum["DecompressTest_" + image.Name], TestTools.ComputeSHA1(image.Data, image.DataSize)); //Console.WriteLine("DecompressTest_" + image.Name + "." + TestTools.ComputeSHA1(image.Data, image.DataSize)); } public static void CompressTest(TexImage image, ITexLibrary library, PixelFormat format) { - Assert.True(!image.Format.IsCompressed); + Assert.False(image.Format.IsCompressed); library.Execute(image, new CompressingRequest(format)); - Assert.True(image.Format == format); + Assert.Equal(image.Format, format); Assert.Equal(TestTools.GetInstance().Checksum["CompressTest_" + format + "_" + image.Name], TestTools.ComputeSHA1(image.Data, image.DataSize)); //Console.WriteLine("CompressTest_" + format + "_" + image.Name + "." + TestTools.ComputeSHA1(image.Data, image.DataSize)); } public static void GenerateMipMapTest(TexImage image, ITexLibrary library, Filter.MipMapGeneration filter) { - Assert.True(image.MipmapCount == 1); + Assert.Equal(1, image.MipmapCount); if (image.Format.IsCompressed) library.Execute(image, new DecompressingRequest(false)); library.Execute(image, new MipMapsGenerationRequest(filter)); Assert.True(image.MipmapCount > 1); @@ -161,7 +161,7 @@ public static void ExportMinMipMapTest(TexImage image, ITexLibrary library, int image.Update(); image2.Update(); - Assert.True(image.Dimension == image2.Dimension); + Assert.Equal(image.Dimension, image2.Dimension); Assert.True(image2.SubImageArray[image2.SubImageArray.Length - 1].Width >= minMipMapSize); Assert.True(image2.SubImageArray[image2.SubImageArray.Length - 1].Height >= minMipMapSize); Assert.True(image.Width == image2.Width); diff --git a/sources/tests/tools/Stride.TextureConverter.Tests/TextureToolTest.cs b/sources/tests/tools/Stride.TextureConverter.Tests/TextureToolTest.cs index d3aea686db..69f2878eb2 100644 --- a/sources/tests/tools/Stride.TextureConverter.Tests/TextureToolTest.cs +++ b/sources/tests/tools/Stride.TextureConverter.Tests/TextureToolTest.cs @@ -26,11 +26,11 @@ public void LoadTest() TexImage img; img = texTool.Load(Module.PathToInputImages + "stones.png"); - Assert.True(img.ArraySize == 1); - Assert.True(img.Width == 512); - Assert.True(img.Height == 512); - Assert.True(img.Depth == 1); - Assert.True(img.Format == PixelFormat.B8G8R8A8_UNorm); + Assert.Equal(1, img.ArraySize); + Assert.Equal(512, img.Width); + Assert.Equal(512, img.Height); + Assert.Equal(1, img.Depth); + Assert.Equal(PixelFormat.B8G8R8A8_UNorm, img.Format); img.Dispose(); try @@ -52,7 +52,7 @@ public void DecompressTest() // ------------------- Test with BC3 image ------------------- img = texTool.Load(Module.PathToInputImages + "TextureArray_WMipMaps_BC3.dds"); - Assert.True(img.Format == PixelFormat.BC3_UNorm); + Assert.Equal(PixelFormat.BC3_UNorm, img.Format); mipmapCount = img.MipmapCount; arraySize = img.ArraySize; width = img.Width; @@ -61,7 +61,7 @@ public void DecompressTest() subImageArrayLenght = img.SubImageArray.Length; texTool.Decompress(img, false); - Assert.True(img.Format == PixelFormat.R8G8B8A8_UNorm); + Assert.Equal(PixelFormat.R8G8B8A8_UNorm, img.Format); Assert.True(mipmapCount == img.MipmapCount); Assert.True(arraySize == img.ArraySize); Assert.True(width == img.Width); @@ -75,7 +75,7 @@ public void DecompressTest() // ------------------- Test with uncompress image ------------------- img = texTool.Load(Module.PathToInputImages + "stones.png"); texTool.Decompress(img, false); - Assert.True(img.Format == PixelFormat.B8G8R8A8_UNorm); //FITexLibrary loads image in BGRA order... + Assert.Equal(PixelFormat.B8G8R8A8_UNorm, img.Format); //FITexLibrary loads image in BGRA order... img.Dispose(); } @@ -120,7 +120,7 @@ public void CompressTest(string filename, PixelFormat format) { TexImage image = texTool.Load(Module.PathToInputImages + filename); texTool.Compress(image, format); - Assert.True(image.Format == format); + Assert.Equal(image.Format, format); Assert.Equal(TestTools.GetInstance().Checksum["TextureTool_Compress_" + format + "_" + image.Name], TestTools.ComputeSHA1(image.Data, image.DataSize)); //Console.WriteLine("TextureTool_Compress_" + format + "_" + image.Name + "." + TestTools.ComputeSHA1(image.Data, image.DataSize)); @@ -212,7 +212,7 @@ public void RescaleTest(string file) texTool.Rescale(image, 0.5f, 0.5f, Filter.Rescaling.Bicubic); Assert.True(image.Width == width / 2); Assert.True(image.Height == height / 2); - Assert.True(image.MipmapCount == 1); + Assert.Equal(1, image.MipmapCount); Assert.Equal(TestTools.GetInstance().Checksum["TextureTool_Rescale_" + image.Name], TestTools.ComputeSHA1(image.Data, image.DataSize)); //Console.WriteLine("TextureTool_Rescale_" + image.Name + "." + TestTools.ComputeSHA1(image.Data, image.DataSize)); @@ -232,7 +232,7 @@ public void ResizeTest(string file) texTool.Resize(image, width/2, height/2, Filter.Rescaling.Bicubic); Assert.True(image.Width == width / 2); Assert.True(image.Height == height / 2); - Assert.True(image.MipmapCount == 1); + Assert.Equal(1, image.MipmapCount); Assert.Equal(TestTools.GetInstance().Checksum["TextureTool_Rescale_" + image.Name], TestTools.ComputeSHA1(image.Data, image.DataSize)); //Console.WriteLine("TextureTool_Rescale_" + image.Name + "." + TestTools.ComputeSHA1(image.Data, image.DataSize)); diff --git a/sources/tools/Stride.FreeImage/Classes/MemoryArray.cs b/sources/tools/Stride.FreeImage/Classes/MemoryArray.cs index b736f2f693..d2df9ef434 100644 --- a/sources/tools/Stride.FreeImage/Classes/MemoryArray.cs +++ b/sources/tools/Stride.FreeImage/Classes/MemoryArray.cs @@ -81,7 +81,7 @@ public unsafe class MemoryArray : IDisposable, ICloneable, ICollection, IEnum static MemoryArray() { T[] dummy = new T[2]; - long marshalledSize = Marshal.SizeOf(typeof(T)); + long marshalledSize = Marshal.SizeOf(); long structureSize = Marshal.UnsafeAddrOfPinnedArrayElement(dummy, 1).ToInt64() - Marshal.UnsafeAddrOfPinnedArrayElement(dummy, 0).ToInt64(); diff --git a/sources/tools/Stride.FreeImage/Classes/Scanline.cs b/sources/tools/Stride.FreeImage/Classes/Scanline.cs index 3fcd6cb418..3058c6ba28 100644 --- a/sources/tools/Stride.FreeImage/Classes/Scanline.cs +++ b/sources/tools/Stride.FreeImage/Classes/Scanline.cs @@ -32,7 +32,7 @@ public Scanline(FIBITMAP dib, int scanline) FreeImage.GetBPP(dib) * FreeImage.GetWidth(dib) : typeof(T) == typeof(FI4BIT) ? FreeImage.GetBPP(dib) * FreeImage.GetWidth(dib) / 4 : - (FreeImage.GetBPP(dib) * FreeImage.GetWidth(dib)) / (Marshal.SizeOf(typeof(T)) * 8))) + (FreeImage.GetBPP(dib) * FreeImage.GetWidth(dib)) / (Marshal.SizeOf() * 8))) { } diff --git a/sources/tools/Stride.FreeImage/FreeImageWrapper.cs b/sources/tools/Stride.FreeImage/FreeImageWrapper.cs index 7686d5f4c7..8fdabfd055 100644 --- a/sources/tools/Stride.FreeImage/FreeImageWrapper.cs +++ b/sources/tools/Stride.FreeImage/FreeImageWrapper.cs @@ -59,7 +59,7 @@ internal static partial class FreeImage /// Array containing all 'FREE_IMAGE_MDMODEL's. /// public static readonly FREE_IMAGE_MDMODEL[] FREE_IMAGE_MDMODELS = - (FREE_IMAGE_MDMODEL[])Enum.GetValues(typeof(FREE_IMAGE_MDMODEL)); + Enum.GetValues(); /// /// Stores handles used to read from streams. diff --git a/sources/tools/Stride.SamplesTestServer/SamplesTestServer.cs b/sources/tools/Stride.SamplesTestServer/SamplesTestServer.cs index 2b39ab193d..75b6a00bdc 100644 --- a/sources/tools/Stride.SamplesTestServer/SamplesTestServer.cs +++ b/sources/tools/Stride.SamplesTestServer/SamplesTestServer.cs @@ -424,12 +424,12 @@ protected override async void HandleClient(SimpleSocket clientSocket, string url var imageData = new TestResultImage(); var stream = new MemoryStream(request.Data); imageData.Read(new BinaryReader(stream)); - stream.Dispose(); + await stream.DisposeAsync(); // Ensure directory exists Directory.CreateDirectory(Path.GetDirectoryName(request.FileName)); var resultFileStream = File.OpenWrite(request.FileName); imageData.Image.Save(resultFileStream, ImageFileType.Png); - resultFileStream.Dispose(); + await resultFileStream.DisposeAsync(); await tester.TesterSocket.Send(new ScreenshotStored()); }); diff --git a/sources/tools/Stride.TextureConverter/Backend/Wrappers/DxtNetWrapper.cs b/sources/tools/Stride.TextureConverter/Backend/Wrappers/DxtNetWrapper.cs index 886525d4dc..70adbbd0a7 100644 --- a/sources/tools/Stride.TextureConverter/Backend/Wrappers/DxtNetWrapper.cs +++ b/sources/tools/Stride.TextureConverter/Backend/Wrappers/DxtNetWrapper.cs @@ -827,7 +827,7 @@ public bool OverrideFormat(TexMetadata mdata, DXGI_FORMAT f) public TexMetadata metadata { - get {return (TexMetadata)Marshal.PtrToStructure(dxtGetMetadata(ptr), typeof(TexMetadata));} + get {return Marshal.PtrToStructure(dxtGetMetadata(ptr)); } } public IntPtr data @@ -847,7 +847,7 @@ public int imageCount public DxtImage GetImage(int mip, int item, int slice) { - return (DxtImage)Marshal.PtrToStructure(dxtGetImage(ptr, mip, item, slice), typeof(DxtImage)); + return Marshal.PtrToStructure(dxtGetImage(ptr, mip, item, slice)); } public DxtImage[] GetImages() @@ -860,7 +860,7 @@ public DxtImage[] GetImages() for(int i=0;i(imagesPtr + i * Marshal.SizeOf(dxtImages[0])); } return dxtImages; @@ -931,7 +931,7 @@ internal static int GetAlphaDepth(String filePath) int headerSize = sizeof(DDSHeaderDX9); // 128byte byte[] buffer = new byte[headerSize]; DDSHeaderDX9 header; - fileStream.Read(buffer, 0, headerSize); + fileStream.ReadExactly(buffer, 0, headerSize); fixed (byte* ptr = buffer) { DDSHeaderDX9* headerPtr = &header; diff --git a/sources/tools/Stride.TextureConverter/Frontend/Console/Program.cs b/sources/tools/Stride.TextureConverter/Frontend/Console/Program.cs index c06026909b..f864fadada 100644 --- a/sources/tools/Stride.TextureConverter/Frontend/Console/Program.cs +++ b/sources/tools/Stride.TextureConverter/Frontend/Console/Program.cs @@ -68,7 +68,7 @@ public override string GetUsageFooter() { var supportedFormat = new StringBuilder(); supportedFormat.AppendLine(); - supportedFormat.AppendFormat("Supported format: {0}", string.Join(", ", Enum.GetNames(typeof(PixelFormat)))); + supportedFormat.AppendFormat("Supported format: {0}", string.Join(", ", Enum.GetNames())); return supportedFormat.ToString(); }