From 88cef7e853aca5736921b97550a09ded48afd93b Mon Sep 17 00:00:00 2001 From: KeatonTheBot Date: Wed, 15 Jul 2026 11:58:24 -0500 Subject: [PATCH] misc: chore: Use explicit types & fix object creation --- .../CodeGen/Arm64/Arm64Optimizer.cs | 4 +- src/ARMeilleure/CodeGen/Arm64/Assembler.cs | 2 +- .../CodeGen/Arm64/CodeGenContext.cs | 4 +- .../CodeGen/Arm64/CodeGenerator.cs | 4 +- src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs | 2 +- .../RegisterAllocators/LinearScanAllocator.cs | 2 +- .../RegisterAllocators/LiveIntervalList.cs | 4 +- .../CodeGen/RegisterAllocators/UseList.cs | 4 +- src/ARMeilleure/CodeGen/X86/Assembler.cs | 15 +- src/ARMeilleure/CodeGen/X86/CodeGenerator.cs | 4 +- .../CodeGen/X86/HardwareCapabilities.cs | 2 +- src/ARMeilleure/CodeGen/X86/PreAllocator.cs | 2 +- src/ARMeilleure/CodeGen/X86/X86Optimizer.cs | 4 +- src/ARMeilleure/Common/BitMap.cs | 6 +- src/ARMeilleure/Common/EntryTable.cs | 8 +- .../Decoders/OpCode32SimdDupElem.cs | 2 +- .../Decoders/OpCode32SimdMovGpElem.cs | 2 +- src/ARMeilleure/Decoders/OpCodeAluImm.cs | 2 +- src/ARMeilleure/Decoders/OpCodeBfm.cs | 2 +- .../Decoders/Optimizations/TailCallRemover.cs | 2 +- src/ARMeilleure/Diagnostics/IRDumper.cs | 4 +- src/ARMeilleure/Instructions/InstEmitAlu32.cs | 4 +- .../Instructions/InstEmitFlowHelper.cs | 5 +- .../Instructions/InstEmitMemoryEx32.cs | 4 +- .../Instructions/InstEmitSimdCmp32.cs | 2 +- .../Instructions/InstEmitSimdCvt32.cs | 8 +- .../Instructions/InstEmitSimdMemory32.cs | 2 +- src/ARMeilleure/Instructions/SoftFloat.cs | 4 +- .../IntermediateRepresentation/Operand.cs | 8 +- src/ARMeilleure/Signal/TestMethods.cs | 4 +- src/ARMeilleure/Translation/Cache/JitCache.cs | 2 +- .../Translation/Cache/JitUnwindWindows.cs | 4 +- .../Translation/ControlFlowGraph.cs | 8 +- src/ARMeilleure/Translation/PTC/Ptc.cs | 19 +- .../Translation/PTC/PtcProfiler.cs | 6 +- .../Translation/SsaConstruction.cs | 6 +- src/ARMeilleure/Translation/Translator.cs | 14 +- .../Translation/TranslatorStubs.cs | 38 +- src/LibKenjinx/Android/Interop.cs | 36 +- src/LibKenjinx/Android/JniExportedMethods.cs | 127 +++---- src/LibKenjinx/LibKenjinx.Device.cs | 8 +- src/LibKenjinx/LibKenjinx.Graphics.cs | 11 +- src/LibKenjinx/LibKenjinx.Input.cs | 22 +- src/LibKenjinx/LibKenjinx.Native.cs | 75 ++-- src/LibKenjinx/LibKenjinx.NativeHelpers.cs | 9 +- src/LibKenjinx/LibKenjinx.User.cs | 22 +- src/LibKenjinx/LibKenjinx.cs | 68 ++-- src/LibKenjinx/VulkanLoader.cs | 12 +- .../SDL3HardwareDeviceDriver.cs | 2 +- .../Native/SoundIoOutStreamContext.cs | 6 +- .../Renderer/Utils/FileHardwareDevice.cs | 2 +- src/Ryujinx.Common/AsyncWorkQueue.cs | 2 +- .../Extensions/SequenceReaderExtensions.cs | 7 +- .../Formatters/DynamicObjectFormatter.cs | 4 +- src/Ryujinx.Common/Logging/Logger.cs | 6 +- .../Logging/Targets/AsyncLogTargetWrapper.cs | 2 +- .../Logging/Targets/JsonLogTarget.cs | 2 +- .../Utilities/EmbeddedResources.cs | 36 +- .../Utilities/FileSystemUtils.cs | 4 +- .../Utilities/MessagePackObjectFormatter.cs | 17 +- src/Ryujinx.Common/Utilities/StreamUtils.cs | 3 +- .../Utilities/XCIFileTrimmer.cs | 18 +- src/Ryujinx.Cpu/AddressTable.cs | 14 +- src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs | 2 +- .../AppleHv/HvMemoryBlockAllocator.cs | 2 +- src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs | 8 +- src/Ryujinx.Cpu/AppleHv/HvVcpu.cs | 2 +- src/Ryujinx.Cpu/AppleHv/HvVm.cs | 2 +- .../Jit/HostTracked/AddressSpacePartition.cs | 2 +- src/Ryujinx.Cpu/Jit/MemoryManager.cs | 8 +- .../Jit/MemoryManagerHostMapped.cs | 2 +- .../Jit/MemoryManagerHostNoMirror.cs | 8 +- .../Jit/MemoryManagerHostTracked.cs | 6 +- .../Arm32/Target/Arm64/InstEmitFlow.cs | 2 +- .../Arm64/Target/Arm64/InstEmitSystem.cs | 2 +- .../LightningJit/Cache/JitCache.cs | 2 +- .../LightningJit/Cache/NoWxCache.cs | 2 +- .../LightningJit/CodeGen/Arm64/Assembler.cs | 10 +- src/Ryujinx.Cpu/LightningJit/Translator.cs | 4 +- .../LightningJit/TranslatorStubs.cs | 2 +- src/Ryujinx.Cpu/Nce/Arm64/Assembler.cs | 10 +- src/Ryujinx.Cpu/Nce/MemoryManagerNative.cs | 8 +- src/Ryujinx.Cpu/Nce/NceCpuCodePatch.cs | 2 +- src/Ryujinx.Cpu/Nce/NceExecutionContext.cs | 4 +- src/Ryujinx.Cpu/Nce/NcePatcher.cs | 2 +- src/Ryujinx.Cpu/PrivateMemoryAllocator.cs | 14 +- src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs | 2 +- src/Ryujinx.Graphics.Device/DeviceState.cs | 11 +- .../Multithreading/ThreadedPipeline.cs | 2 +- .../Multithreading/ThreadedRenderer.cs | 14 +- src/Ryujinx.Graphics.GAL/ResourceLayout.cs | 2 +- .../Engine/Compute/ComputeClass.cs | 5 +- .../Engine/DeviceStateWithShadow.cs | 2 +- .../Engine/Dma/DmaClass.cs | 16 +- .../Engine/GPFifo/GPFifoProcessor.cs | 2 +- .../InlineToMemory/InlineToMemoryClass.cs | 11 +- .../Engine/MME/MacroHLE.cs | 64 ++-- .../Engine/MME/MacroHLETable.cs | 6 +- .../Engine/MME/MacroInterpreter.cs | 2 +- .../Engine/MME/MacroJitContext.cs | 2 +- .../Threed/Blender/AdvancedBlendFunctions.cs | 2 +- .../Threed/Blender/AdvancedBlendManager.cs | 2 +- .../Threed/ComputeDraw/VtgAsComputeContext.cs | 4 +- .../Threed/ComputeDraw/VtgAsComputeState.cs | 8 +- .../Engine/Threed/ConstantBufferUpdater.cs | 9 +- .../Engine/Threed/DrawManager.cs | 16 +- .../Threed/SpecializationStateUpdater.cs | 2 +- .../Engine/Threed/StateUpdateTracker.cs | 15 +- .../Engine/Threed/StateUpdater.cs | 77 ++-- .../Engine/Threed/ThreedClass.cs | 40 +-- .../Engine/Twod/TwodClass.cs | 21 +- src/Ryujinx.Graphics.Gpu/GpuChannel.cs | 6 +- src/Ryujinx.Graphics.Gpu/GpuContext.cs | 16 +- .../Image/AutoDeleteCache.cs | 8 +- src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs | 2 +- src/Ryujinx.Graphics.Gpu/Image/Texture.cs | 10 +- .../Image/TextureCache.cs | 10 +- .../Image/TextureGroup.cs | 44 +-- src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs | 6 +- src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs | 8 +- .../Memory/BufferBackingState.cs | 4 +- .../Memory/BufferCache.cs | 4 +- .../Memory/BufferManager.cs | 38 +- .../Memory/BufferUpdater.cs | 2 +- .../Memory/GpuRegionHandle.cs | 12 +- .../Memory/MemoryManager.cs | 2 +- .../Memory/MultiRangeBuffer.cs | 4 +- .../Memory/PhysicalMemory.cs | 18 +- .../Memory/SupportBufferUpdater.cs | 2 +- .../Shader/CachedShaderBindings.cs | 4 +- .../Shader/ComputeShaderCacheHashTable.cs | 6 +- .../Shader/DiskCache/DiskCacheGuestStorage.cs | 14 +- .../Shader/DiskCache/DiskCacheHostStorage.cs | 44 +-- .../DiskCache/ParallelDiskCacheLoader.cs | 4 +- .../Shader/GpuAccessor.cs | 3 +- .../Shader/ShaderCache.cs | 22 +- .../Shader/ShaderCacheHashTable.cs | 8 +- .../Shader/ShaderInfoBuilder.cs | 4 +- .../Shader/ShaderSpecializationList.cs | 4 +- .../Shader/ShaderSpecializationState.cs | 34 +- .../Synchronization/SynchronizationManager.cs | 2 +- src/Ryujinx.Graphics.Gpu/Window.cs | 3 +- src/Ryujinx.Graphics.Host1x/Devices.cs | 2 +- src/Ryujinx.Graphics.Host1x/Host1xDevice.cs | 2 +- .../Native/FFmpegApi.cs | 2 +- .../Image/SurfaceWriter.cs | 13 +- src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs | 4 +- src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs | 7 +- .../Effects/AreaScalingFilter.cs | 2 +- .../Effects/FsrScalingFilter.cs | 14 +- .../Effects/FxaaPostProcessingEffect.cs | 6 +- .../Effects/ShaderHelper.cs | 4 +- .../Effects/SmaaPostProcessingEffect.cs | 49 +-- .../Image/FormatConverter.cs | 24 +- .../Image/TextureBuffer.cs | 2 +- .../Image/TextureCopyIncompatible.cs | 4 +- .../Image/TextureView.cs | 2 +- src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs | 3 +- src/Ryujinx.Graphics.OpenGL/Pipeline.cs | 2 +- .../Queries/Counters.cs | 4 +- src/Ryujinx.Graphics.OpenGL/VertexArray.cs | 4 +- src/Ryujinx.Graphics.OpenGL/Window.cs | 8 +- .../CodeGen/Glsl/Declarations.cs | 18 +- .../CodeGen/Glsl/Instructions/InstGenCall.cs | 2 +- .../Glsl/Instructions/InstGenMemory.cs | 2 +- .../CodeGen/Spirv/CodeGenContext.cs | 18 +- .../CodeGen/Spirv/Declarations.cs | 96 ++--- .../CodeGen/Spirv/Instructions.cs | 338 +++++++++--------- .../CodeGen/Spirv/SpirvGenerator.cs | 38 +- .../Decoders/Decoder.cs | 14 +- .../Instructions/AttributeMap.cs | 4 +- .../Instructions/InstEmitAttribute.cs | 2 +- .../Instructions/InstEmitBitfield.cs | 36 +- .../Instructions/InstEmitConversion.cs | 24 +- .../Instructions/InstEmitFloatArithmetic.cs | 172 ++++----- .../Instructions/InstEmitFloatComparison.cs | 98 ++--- .../Instructions/InstEmitFloatMinMax.cs | 36 +- .../Instructions/InstEmitFlowControl.cs | 12 +- .../Instructions/InstEmitIntegerArithmetic.cs | 146 ++++---- .../Instructions/InstEmitIntegerComparison.cs | 50 +-- .../Instructions/InstEmitIntegerLogical.cs | 34 +- .../Instructions/InstEmitIntegerMinMax.cs | 18 +- .../Instructions/InstEmitShift.cs | 36 +- .../Instructions/InstEmitTexture.cs | 12 +- .../StructuredIr/ShaderProperties.cs | 4 +- .../Translation/EmitterContext.cs | 5 +- .../Translation/FunctionMatch.cs | 32 +- .../Optimizations/GlobalToStorage.cs | 4 +- .../Translation/RegisterUsage.cs | 2 +- .../Translation/ResourceManager.cs | 30 +- .../Translation/ShaderDefinitions.cs | 8 +- .../Translation/Translator.cs | 4 +- .../Translation/TranslatorContext.cs | 48 +-- .../Encoders/BC7Encoder.cs | 2 +- src/Ryujinx.Graphics.Vulkan/Auto.cs | 2 +- .../BackgroundResources.cs | 2 +- src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs | 4 +- src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs | 8 +- src/Ryujinx.Graphics.Vulkan/BufferHolder.cs | 48 +-- src/Ryujinx.Graphics.Vulkan/BufferManager.cs | 84 ++--- .../BufferMirrorRangeList.cs | 20 +- src/Ryujinx.Graphics.Vulkan/BufferState.cs | 3 +- .../CommandBufferPool.cs | 30 +- .../DescriptorSetCollection.cs | 14 +- .../DescriptorSetManager.cs | 14 +- .../DescriptorSetTemplate.cs | 4 +- .../DescriptorSetUpdater.cs | 63 ++-- .../Effects/AreaScalingFilter.cs | 6 +- .../Effects/FsrScalingFilter.cs | 16 +- .../Effects/FxaaPostProcessingEffect.cs | 10 +- .../Effects/SmaaPostProcessingEffect.cs | 29 +- src/Ryujinx.Graphics.Vulkan/FenceHolder.cs | 2 +- .../FormatCapabilities.cs | 14 +- .../FramebufferParams.cs | 14 +- src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs | 14 +- src/Ryujinx.Graphics.Vulkan/HelperShader.cs | 149 ++++---- .../HostMemoryAllocator.cs | 14 +- src/Ryujinx.Graphics.Vulkan/ImageArray.cs | 4 +- .../IndexBufferState.cs | 2 +- .../MemoryAllocator.cs | 4 +- .../MemoryAllocatorBlockList.cs | 14 +- .../MoltenVK/MVKInitialization.cs | 3 +- .../MultiFenceHolder.cs | 4 +- .../PersistentFlushBuffer.cs | 26 +- src/Ryujinx.Graphics.Vulkan/PipelineBase.cs | 116 +++--- .../PipelineConverter.cs | 22 +- src/Ryujinx.Graphics.Vulkan/PipelineFull.cs | 10 +- .../PipelineLayoutCache.cs | 6 +- .../PipelineLayoutCacheEntry.cs | 32 +- .../PipelineLayoutFactory.cs | 4 +- src/Ryujinx.Graphics.Vulkan/PipelineState.cs | 36 +- .../Queries/BufferedQuery.cs | 7 +- .../Queries/Counters.cs | 6 +- .../RenderPassCacheKey.cs | 2 +- .../RenderPassHolder.cs | 20 +- src/Ryujinx.Graphics.Vulkan/ResourceArray.cs | 2 +- .../ResourceLayoutBuilder.cs | 4 +- src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs | 8 +- src/Ryujinx.Graphics.Vulkan/Shader.cs | 4 +- .../ShaderCollection.cs | 22 +- src/Ryujinx.Graphics.Vulkan/SpecInfo.cs | 4 +- src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs | 14 +- src/Ryujinx.Graphics.Vulkan/TextureArray.cs | 4 +- src/Ryujinx.Graphics.Vulkan/TextureCopy.cs | 54 +-- src/Ryujinx.Graphics.Vulkan/TextureStorage.cs | 44 +-- src/Ryujinx.Graphics.Vulkan/TextureView.cs | 120 +++---- .../VertexBufferState.cs | 7 +- .../VulkanDebugMessenger.cs | 4 +- .../VulkanInitialization.cs | 47 +-- .../VulkanPhysicalDevice.cs | 2 +- src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs | 29 +- src/Ryujinx.Graphics.Vulkan/Window.cs | 60 ++-- .../IpcServiceGenerator.cs | 15 +- .../ServiceNotImplementedException.cs | 23 +- src/Ryujinx.HLE/FileSystem/ContentManager.cs | 100 +++--- src/Ryujinx.HLE/FileSystem/ContentMetaData.cs | 2 +- .../FileSystem/VirtualFileSystem.cs | 26 +- .../HOS/Applets/Error/ErrorApplet.cs | 2 +- .../SoftwareKeyboardApplet.cs | 16 +- .../SoftwareKeyboardRenderer.cs | 4 +- .../SoftwareKeyboardRendererBase.cs | 78 ++-- .../Applets/SoftwareKeyboard/TimedAction.cs | 10 +- .../HOS/ArmProcessContextFactory.cs | 18 +- .../HOS/Diagnostics/Demangler/Demangler.cs | 2 +- src/Ryujinx.HLE/HOS/Horizon.cs | 16 +- src/Ryujinx.HLE/HOS/HorizonFsClient.cs | 6 +- .../HOS/Kernel/Memory/KMemoryManager.cs | 4 +- .../HOS/Kernel/Memory/KMemoryRegionManager.cs | 2 +- .../HOS/Kernel/Memory/KPageBitmap.cs | 2 +- .../HOS/Kernel/Memory/KPageHeap.cs | 2 +- .../HOS/Kernel/Memory/KPageList.cs | 4 +- .../HOS/Kernel/Memory/KPageTable.cs | 18 +- .../HOS/Kernel/Memory/KPageTableBase.cs | 12 +- .../HOS/Kernel/Process/HleProcessDebugger.cs | 19 +- .../HOS/Kernel/SupervisorCall/Syscall.cs | 6 +- .../HOS/Kernel/Threading/KPriorityQueue.cs | 4 +- .../HOS/Kernel/Threading/KThread.cs | 2 +- src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs | 2 +- src/Ryujinx.HLE/HOS/ModLoader.cs | 95 ++--- .../Services/Account/Acc/AccountManager.cs | 4 +- .../Account/Acc/AccountSaveDataManager.cs | 5 +- .../Acc/AccountService/ManagerServer.cs | 2 +- .../SystemAppletProxy/ICommonStateGetter.cs | 2 +- .../ApplicationProxy/IApplicationFunctions.cs | 5 +- .../HOS/Services/Caps/CaptureManager.cs | 4 +- .../FileSystemProxy/FileSystemProxyHelper.cs | 10 +- .../Services/Fs/FileSystemProxy/IDirectory.cs | 3 +- .../HOS/Services/Fs/FileSystemProxy/IFile.cs | 3 +- .../Fs/FileSystemProxy/IFileSystem.cs | 4 +- .../Services/Fs/FileSystemProxy/IStorage.cs | 3 +- .../HOS/Services/Fs/ISaveDataInfoReader.cs | 3 +- .../HOS/Services/Hid/Irs/IIrSensorServer.cs | 8 +- .../LdnMitm/LanDiscovery.cs | 2 +- .../LdnMitm/Proxy/LdnProxyUdpServer.cs | 4 +- .../LdnRyu/LdnMasterProxyClient.cs | 4 +- .../LdnRyu/Proxy/LdnProxySocket.cs | 2 +- .../HOS/Services/Mii/Types/CoreData.cs | 24 +- .../Nfc/AmiiboDecryption/AmiiboDecryptor.cs | 4 +- .../Nfc/AmiiboDecryption/AmiiboDump.cs | 20 +- .../HOS/Services/Nfc/Nfp/NfpManager/INfp.cs | 18 +- .../HOS/Services/Nv/Host1xContext.cs | 4 +- .../NvHostAsGpu/NvHostAsGpuDeviceFile.cs | 6 +- .../NvHostAsGpu/Types/AddressSpaceContext.cs | 2 +- .../NvHostChannel/NvHostChannelDeviceFile.cs | 2 +- .../IParentalControlService.cs | 3 +- .../QueryPlayStatisticsManager.cs | 2 +- .../HOS/Services/Sdb/Pl/SharedFontManager.cs | 2 +- src/Ryujinx.HLE/HOS/Services/ServerBase.cs | 11 +- .../Settings/ISystemSettingsServer.cs | 2 +- .../HOS/Services/Sockets/Bsd/IClient.cs | 6 +- .../Sockets/Bsd/Impl/WinSockHelper.cs | 4 +- .../Sockets/Bsd/Proxy/SocketHelpers.cs | 6 +- .../Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs | 2 +- .../Services/Ssl/BuiltInCertificateManager.cs | 2 +- .../Services/Ssl/SslService/ISslConnection.cs | 2 +- .../Time/TimeZone/TimeZoneContentManager.cs | 12 +- .../CodeEmitters/EndConditionalBlock.cs | 2 +- .../HOS/Tamper/InstructionHelper.cs | 2 +- src/Ryujinx.HLE/HOS/TamperMachine.cs | 6 +- src/Ryujinx.HLE/Kenjinx/AmiiboBridge.cs | 34 +- .../Loaders/Executables/KipExecutable.cs | 2 +- .../Loaders/Executables/NsoExecutable.cs | 2 +- src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs | 4 +- .../Loaders/Mods/IPSwitchPatcher.cs | 8 +- src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs | 4 +- .../Extensions/FileSystemExtensions.cs | 2 +- .../Extensions/LocalFileSystemExtensions.cs | 2 +- .../Extensions/MetaLoaderExtensions.cs | 8 +- .../Processes/Extensions/NcaExtensions.cs | 8 +- .../PartitionFileSystemExtensions.cs | 4 +- .../Loaders/Processes/ProcessLoader.cs | 4 +- src/Ryujinx.HLE/UI/Input/NpadReader.cs | 11 +- .../Utilities/PartitionFileSystemUtils.cs | 2 +- .../Hipc/HipcGenerator.cs | 24 +- .../Hipc/HipcSyntaxReceiver.cs | 4 +- .../SyscallGenerator.cs | 8 +- .../SyscallSyntaxReceiver.cs | 2 +- .../Bcat/Ipc/ServiceCreator.cs | 8 +- .../DeliveryCacheStorageService.cs | 8 +- src/Ryujinx.Horizon/HeapAllocator.cs | 6 +- src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs | 2 +- .../Sdk/Audio/Detail/AudioInManager.cs | 3 +- .../Sdk/Audio/Detail/AudioOutManager.cs | 3 +- .../Sdk/Audio/Detail/AudioRendererManager.cs | 9 +- src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs | 2 +- .../Sdk/Ngc/Detail/CompressedArray.cs | 4 +- .../Sdk/OsTypes/OsSystemEvent.cs | 2 +- src/Ryujinx.Horizon/Sdk/ServiceUtil.cs | 5 +- .../Cmif/DomainServiceObjectDispatchTable.cs | 6 +- .../Sf/Cmif/DomainServiceObjectProcessor.cs | 4 +- .../Sdk/Sf/Cmif/ServerDomainManager.cs | 16 +- .../Sdk/Sf/Cmif/ServiceDispatchTableBase.cs | 6 +- src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs | 2 +- .../Sdk/Sf/CommandSerialization.cs | 2 +- src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs | 4 +- .../Sdk/Sf/Hipc/HipcManager.cs | 6 +- .../Sdk/Sf/Hipc/ServerManagerBase.cs | 5 +- .../Sdk/Sf/Hipc/ServerSessionManager.cs | 6 +- .../Sdk/Sf/HipcCommandProcessor.cs | 26 +- src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs | 2 +- src/Ryujinx.Input.SDL3/SDL3GamepadDriver.cs | 12 +- src/Ryujinx.Input.SDL3/SDL3JoyCon.cs | 2 +- src/Ryujinx.Input.SDL3/SDL3JoyConPair.cs | 2 +- .../Assigner/GamepadButtonAssigner.cs | 2 +- src/Ryujinx.Input/HLE/NpadController.cs | 4 +- src/Ryujinx.Input/HLE/NpadManager.cs | 11 +- src/Ryujinx.Input/HLE/TouchScreenManager.cs | 5 +- src/Ryujinx.Input/Motion/CemuHook/Client.cs | 10 +- src/Ryujinx.Memory/AddressSpaceManager.cs | 8 +- .../BytesReadOnlySequenceSegment.cs | 6 +- src/Ryujinx.Memory/IVirtualMemoryManager.cs | 2 +- src/Ryujinx.Memory/MemoryManagementWindows.cs | 2 +- src/Ryujinx.Memory/Range/MultiRange.cs | 2 +- src/Ryujinx.Memory/Range/MultiRangeList.cs | 10 +- src/Ryujinx.Memory/Tracking/MemoryTracking.cs | 4 +- .../Tracking/MultiRegionHandle.cs | 4 +- src/Ryujinx.Memory/Tracking/RegionHandle.cs | 6 +- .../Tracking/SmartMultiRegionHandle.cs | 8 +- src/Ryujinx.Memory/Tracking/VirtualRegion.cs | 4 +- .../VirtualMemoryManagerBase.cs | 2 +- .../WindowsShared/PlaceholderManager.cs | 32 +- .../SequenceReaderExtensionsTests.cs | 42 +-- src/Ryujinx.Tests/Cpu/CpuTest32.cs | 2 +- src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs | 4 +- src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs | 18 +- src/Ryujinx.Tests/Cpu/EnvironmentTests.cs | 2 +- src/Ryujinx.Tests/Memory/PartialUnmaps.cs | 43 +-- src/Ryujinx.UI.Common/App/ApplicationData.cs | 6 +- .../App/ApplicationLibrary.cs | 90 ++--- .../Configuration/ConfigurationState.cs | 4 +- .../Configuration/LoggerModule.cs | 4 +- .../Helper/DownloadableContentsHelper.cs | 10 +- .../Helper/FileAssociationHelper.cs | 6 +- src/Ryujinx.UI.Common/Helper/LinuxHelper.cs | 2 +- src/Ryujinx.UI.Common/Helper/OpenHelper.cs | 4 +- .../Helper/ShortcutHelper.cs | 20 +- .../Helper/TitleUpdatesHelper.cs | 14 +- .../Helper/ValueFormatUtils.cs | 4 +- .../Models/XCITrimmerFileModel.cs | 2 +- .../SystemInfo/LinuxSystemInfo.cs | 4 +- .../SystemInfo/MacOSSystemInfo.cs | 4 +- .../SystemInfo/WindowsSystemInfo.cs | 2 +- src/Ryujinx/App.axaml.cs | 6 +- src/Ryujinx/AppHost.cs | 16 +- src/Ryujinx/Common/ApplicationHelper.cs | 22 +- src/Ryujinx/Common/Locale/LocaleManager.cs | 8 +- src/Ryujinx/Headless/HeadlessRyujinx.Init.cs | 4 +- src/Ryujinx/Headless/WindowBase.cs | 6 +- src/Ryujinx/Input/AvaloniaKeyboardDriver.cs | 2 +- .../Input/AvaloniaKeyboardMappingHelper.cs | 6 +- src/Ryujinx/Modules/Updater/Updater.cs | 16 +- src/Ryujinx/UI/Applet/AvaHostUIHandler.cs | 4 +- .../Applet/AvaloniaDynamicTextInputHandler.cs | 4 +- src/Ryujinx/UI/Applet/AvaloniaHostUITheme.cs | 2 +- .../Controls/ApplicationContextMenu.axaml.cs | 40 +-- .../UI/Controls/ApplicationListView.axaml.cs | 5 +- .../UI/Controls/NavigationDialogHost.axaml.cs | 22 +- src/Ryujinx/UI/Controls/SliderScroll.axaml.cs | 2 +- .../UI/Helpers/AvaloniaListExtensions.cs | 6 +- src/Ryujinx/UI/Helpers/ContentDialogHelper.cs | 2 +- src/Ryujinx/UI/Helpers/GlyphValueConverter.cs | 2 +- src/Ryujinx/UI/Helpers/LoggerAdapter.cs | 2 +- src/Ryujinx/UI/Helpers/NotificationHelper.cs | 2 +- src/Ryujinx/UI/Helpers/TimeZoneConverter.cs | 2 +- src/Ryujinx/UI/Helpers/UserErrorDialog.cs | 2 +- src/Ryujinx/UI/Models/CheatNode.cs | 2 +- .../UI/Models/Input/GamepadInputConfig.cs | 2 +- src/Ryujinx/UI/Models/Input/HotkeyConfig.cs | 2 +- .../UI/Models/Input/KeyboardInputConfig.cs | 2 +- src/Ryujinx/UI/Models/SaveModel.cs | 12 +- src/Ryujinx/UI/Models/UserProfile.cs | 3 +- .../UI/Renderer/EmbeddedWindowOpenGL.cs | 4 +- .../DownloadableContentManagerViewModel.cs | 18 +- .../UI/ViewModels/Input/InputViewModel.cs | 22 +- .../UI/ViewModels/MainWindowViewModel.cs | 28 +- .../UI/ViewModels/ModManagerViewModel.cs | 42 +-- .../UI/ViewModels/SettingsViewModel.cs | 8 +- .../UI/ViewModels/TitleUpdateViewModel.cs | 20 +- .../UserFirmwareAvatarSelectorViewModel.cs | 6 +- .../UI/ViewModels/XCITrimmerViewModel.cs | 18 +- .../Views/Input/ControllerInputView.axaml.cs | 3 +- src/Ryujinx/UI/Views/Input/InputView.axaml.cs | 4 +- .../UI/Views/Input/KeyboardInputView.axaml.cs | 5 +- .../UI/Views/Input/MotionInputView.axaml.cs | 5 +- .../UI/Views/Input/RumbleInputView.axaml.cs | 5 +- .../UI/Views/Main/MainMenuBarView.axaml.cs | 4 +- .../Settings/SettingsHotkeysView.axaml.cs | 7 +- .../UI/Views/User/UserEditorView.axaml.cs | 2 +- .../UserFirmwareAvatarSelectorView.axaml.cs | 2 +- .../UserProfileImageSelectorView.axaml.cs | 2 +- .../UI/Views/User/UserRecovererView.axaml.cs | 2 +- .../Views/User/UserSaveManagerView.axaml.cs | 14 +- src/Ryujinx/UI/Windows/CheatWindow.axaml.cs | 10 +- .../DownloadableContentManagerWindow.axaml.cs | 4 +- src/Ryujinx/UI/Windows/IconColorPicker.cs | 22 +- src/Ryujinx/UI/Windows/MainWindow.axaml.cs | 12 +- .../UI/Windows/ModManagerWindow.axaml.cs | 12 +- .../UI/Windows/XCITrimmerWindow.axaml.cs | 4 +- src/Spv.Generator/Instruction.cs | 4 +- src/Spv.Generator/InstructionOperands.cs | 6 +- src/Spv.Generator/Module.cs | 8 +- 461 files changed, 3163 insertions(+), 3082 deletions(-) diff --git a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs index 5fd1e0953..112193f46 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs @@ -13,13 +13,13 @@ namespace ARMeilleure.CodeGen.Arm64 public static void RunPass(ControlFlowGraph cfg) { - var constants = new Dictionary(); + Dictionary constants = new(); Operand GetConstantCopy(BasicBlock block, Operation operation, Operand source) { // If the constant has many uses, we also force a new constant mov to be added, in order // to avoid overflow of the counts field (that is limited to 16 bits). - if (!constants.TryGetValue(source.Value, out var constant) || constant.UsesCount > MaxConstantUses) + if (!constants.TryGetValue(source.Value, out Operand constant) || constant.UsesCount > MaxConstantUses) { constant = Local(source.Type); diff --git a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs index 41684faf2..47902ddc8 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs @@ -123,7 +123,7 @@ namespace ARMeilleure.CodeGen.Arm64 public void Cset(Operand rd, ArmCondition condition) { - var zr = Factory.Register(ZrRegister, RegisterType.Integer, rd.Type); + Operand zr = Factory.Register(ZrRegister, RegisterType.Integer, rd.Type); Csinc(rd, zr, zr, (ArmCondition)((int)condition ^ 1)); } diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs index 580feabff..46cd863cf 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs @@ -91,7 +91,7 @@ namespace ARMeilleure.CodeGen.Arm64 long target = _stream.Position; - if (_pendingBranches.TryGetValue(block, out var list)) + if (_pendingBranches.TryGetValue(block, out List<(ArmCondition Condition, long BranchPos)> list)) { foreach ((ArmCondition condition, long branchPos) in list) { @@ -119,7 +119,7 @@ namespace ARMeilleure.CodeGen.Arm64 } else { - if (!_pendingBranches.TryGetValue(target, out var list)) + if (!_pendingBranches.TryGetValue(target, out List<(ArmCondition Condition, long BranchPos)> list)) { list = new List<(ArmCondition, long)>(); _pendingBranches.Add(target, list); diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs index cbc86b320..9307ef67f 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs @@ -321,7 +321,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToArmCondition(); + ArmCondition cond = ((Comparison)comp.AsInt32()).ToArmCondition(); GenerateCompareCommon(context, operation); @@ -353,7 +353,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(dest.Type == OperandType.I32); Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToArmCondition(); + ArmCondition cond = ((Comparison)comp.AsInt32()).ToArmCondition(); GenerateCompareCommon(context, operation); diff --git a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs index 69d4e74c5..ef09ee523 100644 --- a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs @@ -847,7 +847,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(comp.Kind == OperandKind.Constant); - var compType = (Comparison)comp.AsInt32(); + Comparison compType = (Comparison)comp.AsInt32(); return compType is Comparison.Equal or Comparison.NotEqual; } diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs index d78f9f621..dba25b939 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs @@ -115,7 +115,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { NumberLocals(cfg, regMasks.RegistersCount); - var context = new AllocationContext(stackAlloc, regMasks, _intervals.Count); + AllocationContext context = new(stackAlloc, regMasks, _intervals.Count); BuildIntervals(cfg, context); diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs index 84b892f42..b31d8fa78 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs @@ -15,12 +15,12 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { if (_count + 1 > _capacity) { - var oldSpan = Span; + Span oldSpan = Span; _capacity = Math.Max(4, _capacity * 2); _items = Allocators.References.Allocate((uint)_capacity); - var newSpan = Span; + Span newSpan = Span; oldSpan.CopyTo(newSpan); } diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs index 806002f83..c78201785 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs @@ -16,12 +16,12 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { if (Count + 1 > _capacity) { - var oldSpan = Span; + Span oldSpan = Span; _capacity = Math.Max(4, _capacity * 2); _items = Allocators.Default.Allocate((uint)_capacity); - var newSpan = Span; + Span newSpan = Span; oldSpan.CopyTo(newSpan); } diff --git a/src/ARMeilleure/CodeGen/X86/Assembler.cs b/src/ARMeilleure/CodeGen/X86/Assembler.cs index 727e2bc61..f9a0c8700 100644 --- a/src/ARMeilleure/CodeGen/X86/Assembler.cs +++ b/src/ARMeilleure/CodeGen/X86/Assembler.cs @@ -1,5 +1,6 @@ using ARMeilleure.CodeGen.Linking; using ARMeilleure.IntermediateRepresentation; +using Microsoft.IO; using Ryujinx.Common.Memory; using System; using System.Collections.Generic; @@ -1324,8 +1325,8 @@ namespace ARMeilleure.CodeGen.X86 public (byte[], RelocInfo) GetCode() { - var jumps = CollectionsMarshal.AsSpan(_jumps); - var relocs = CollectionsMarshal.AsSpan(_relocs); + Span jumps = CollectionsMarshal.AsSpan(_jumps); + Span relocs = CollectionsMarshal.AsSpan(_relocs); // Write jump relative offsets. bool modified; @@ -1410,13 +1411,13 @@ namespace ARMeilleure.CodeGen.X86 // Write the code, ignoring the dummy bytes after jumps, into a new stream. _stream.Seek(0, SeekOrigin.Begin); - using var codeStream = MemoryStreamManager.Shared.GetStream(); - var assembler = new Assembler(codeStream, HasRelocs); + using RecyclableMemoryStream codeStream = MemoryStreamManager.Shared.GetStream(); + Assembler assembler = new(codeStream, HasRelocs); bool hasRelocs = HasRelocs; int relocIndex = 0; int relocOffset = 0; - var relocEntries = hasRelocs + RelocEntry[] relocEntries = hasRelocs ? new RelocEntry[relocs.Length] : Array.Empty(); @@ -1469,8 +1470,8 @@ namespace ARMeilleure.CodeGen.X86 _stream.CopyTo(codeStream); - var code = codeStream.ToArray(); - var relocInfo = new RelocInfo(relocEntries); + byte[] code = codeStream.ToArray(); + RelocInfo relocInfo = new(relocEntries); return (code, relocInfo); } diff --git a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs index 2e69be5b1..d2408d321 100644 --- a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs @@ -622,7 +622,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToX86Condition(); + X86Condition cond = ((Comparison)comp.AsInt32()).ToX86Condition(); GenerateCompareCommon(context, operation); @@ -660,7 +660,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(dest.Type == OperandType.I32); Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToX86Condition(); + X86Condition cond = ((Comparison)comp.AsInt32()).ToX86Condition(); GenerateCompareCommon(context, operation); diff --git a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs index 467de1bc8..02c0b79f2 100644 --- a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs +++ b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs @@ -53,7 +53,7 @@ namespace ARMeilleure.CodeGen.X86 memGetXcr0.Reprotect(0, (ulong)asmGetXcr0.Length, MemoryPermission.ReadAndExecute); - var fGetXcr0 = Marshal.GetDelegateForFunctionPointer(memGetXcr0.Pointer); + GetXcr0 fGetXcr0 = Marshal.GetDelegateForFunctionPointer(memGetXcr0.Pointer); return fGetXcr0(); } diff --git a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs index a3924d6bf..b9b9f9caf 100644 --- a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs @@ -759,7 +759,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(comp.Kind == OperandKind.Constant); - var compType = (Comparison)comp.AsInt32(); + Comparison compType = (Comparison)comp.AsInt32(); return compType is Comparison.Equal or Comparison.NotEqual; } diff --git a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs index c3dcfcef9..395b874d7 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs @@ -13,13 +13,13 @@ namespace ARMeilleure.CodeGen.X86 public static void RunPass(ControlFlowGraph cfg) { - var constants = new Dictionary(); + Dictionary constants = new(); Operand GetConstantCopy(BasicBlock block, Operation operation, Operand source) { // If the constant has many uses, we also force a new constant mov to be added, in order // to avoid overflow of the counts field (that is limited to 16 bits). - if (!constants.TryGetValue(source.Value, out var constant) || constant.UsesCount > MaxConstantUses) + if (!constants.TryGetValue(source.Value, out Operand constant) || constant.UsesCount > MaxConstantUses) { constant = Local(source.Type); diff --git a/src/ARMeilleure/Common/BitMap.cs b/src/ARMeilleure/Common/BitMap.cs index 94d47ea59..52e192699 100644 --- a/src/ARMeilleure/Common/BitMap.cs +++ b/src/ARMeilleure/Common/BitMap.cs @@ -129,13 +129,13 @@ namespace ARMeilleure.Common if (count > _count) { - var oldMask = _masks; - var oldSpan = new Span(_masks, _count); + long* oldMask = _masks; + Span oldSpan = new(_masks, _count); _masks = _allocator.Allocate((uint)count); _count = count; - var newSpan = new Span(_masks, _count); + Span newSpan = new(_masks, _count); oldSpan.CopyTo(newSpan); newSpan[oldSpan.Length..].Clear(); diff --git a/src/ARMeilleure/Common/EntryTable.cs b/src/ARMeilleure/Common/EntryTable.cs index e49a0989e..7b8c1e134 100644 --- a/src/ARMeilleure/Common/EntryTable.cs +++ b/src/ARMeilleure/Common/EntryTable.cs @@ -63,7 +63,7 @@ namespace ARMeilleure.Common } int index = _freeHint++; - var page = GetPage(index); + Span page = GetPage(index); _allocated.Set(index); @@ -111,7 +111,7 @@ namespace ARMeilleure.Common throw new ArgumentException("Entry at the specified index was not allocated", nameof(index)); } - var page = GetPage(index); + Span page = GetPage(index); return ref GetValue(page, index); } @@ -136,7 +136,7 @@ namespace ARMeilleure.Common /// Page for the specified private unsafe Span GetPage(int index) { - var pageIndex = (int)((uint)(index & ~(_pageCapacity - 1)) >> _pageLogCapacity); + int pageIndex = (int)((uint)(index & ~(_pageCapacity - 1)) >> _pageLogCapacity); if (!_pages.TryGetValue(pageIndex, out nint page)) { @@ -168,7 +168,7 @@ namespace ARMeilleure.Common { _allocated.Dispose(); - foreach (var page in _pages.Values) + foreach (IntPtr page in _pages.Values) { NativeAllocator.Instance.Free((void*)page); } diff --git a/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs b/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs index b6cdff088..fbb14056d 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs @@ -9,7 +9,7 @@ namespace ARMeilleure.Decoders public OpCode32SimdDupElem(InstDescriptor inst, ulong address, int opCode, bool isThumb) : base(inst, address, opCode, isThumb) { - var opc = (opCode >> 16) & 0xf; + int opc = (opCode >> 16) & 0xf; if ((opc & 0b1) == 1) { diff --git a/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs b/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs index f6fce7d99..3b9431da4 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs @@ -21,7 +21,7 @@ namespace ARMeilleure.Decoders Op = (opCode >> 20) & 0x1; U = ((opCode >> 23) & 1) != 0; - var opc = (((opCode >> 23) & 1) << 4) | (((opCode >> 21) & 0x3) << 2) | ((opCode >> 5) & 0x3); + int opc = (((opCode >> 23) & 1) << 4) | (((opCode >> 21) & 0x3) << 2) | ((opCode >> 5) & 0x3); if ((opc & 0b01000) == 0b01000) { diff --git a/src/ARMeilleure/Decoders/OpCodeAluImm.cs b/src/ARMeilleure/Decoders/OpCodeAluImm.cs index 0d2f7202f..41a12e474 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluImm.cs @@ -20,7 +20,7 @@ namespace ARMeilleure.Decoders } else if (DataOp == DataOp.Logical) { - var bm = DecoderHelper.DecodeBitMask(opCode, true); + DecoderHelper.BitMask bm = DecoderHelper.DecodeBitMask(opCode, true); if (bm.IsUndefined) { diff --git a/src/ARMeilleure/Decoders/OpCodeBfm.cs b/src/ARMeilleure/Decoders/OpCodeBfm.cs index d51efade2..969c782f8 100644 --- a/src/ARMeilleure/Decoders/OpCodeBfm.cs +++ b/src/ARMeilleure/Decoders/OpCodeBfm.cs @@ -11,7 +11,7 @@ namespace ARMeilleure.Decoders public OpCodeBfm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - var bm = DecoderHelper.DecodeBitMask(opCode, false); + DecoderHelper.BitMask bm = DecoderHelper.DecodeBitMask(opCode, false); if (bm.IsUndefined) { diff --git a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs index 9d988f0c9..15ab3e6b8 100644 --- a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs +++ b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs @@ -69,7 +69,7 @@ namespace ARMeilleure.Decoders.Optimizations } } - var newBlocks = new List(blocks.Count); + List newBlocks = new(blocks.Count); // Finally, rebuild decoded block list, ignoring blocks outside the contiguous range. for (int i = 0; i < blocks.Count; i++) diff --git a/src/ARMeilleure/Diagnostics/IRDumper.cs b/src/ARMeilleure/Diagnostics/IRDumper.cs index 6c58a3ea6..95314618f 100644 --- a/src/ARMeilleure/Diagnostics/IRDumper.cs +++ b/src/ARMeilleure/Diagnostics/IRDumper.cs @@ -141,7 +141,7 @@ namespace ARMeilleure.Diagnostics break; case OperandKind.Memory: - var memOp = operand.GetMemory(); + MemoryOperand memOp = operand.GetMemory(); _builder.Append('['); @@ -284,7 +284,7 @@ namespace ARMeilleure.Diagnostics public static string GetDump(ControlFlowGraph cfg) { - var dumper = new IRDumper(1); + IRDumper dumper = new(1); for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) { diff --git a/src/ARMeilleure/Instructions/InstEmitAlu32.cs b/src/ARMeilleure/Instructions/InstEmitAlu32.cs index 8eabe093e..2e659fd5f 100644 --- a/src/ARMeilleure/Instructions/InstEmitAlu32.cs +++ b/src/ARMeilleure/Instructions/InstEmitAlu32.cs @@ -415,7 +415,7 @@ namespace ARMeilleure.Instructions { IOpCode32AluBf op = (IOpCode32AluBf)context.CurrOp; - var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. + int msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. Operand n = GetIntA32(context, op.Rn); Operand res = context.ShiftRightSI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb)); @@ -547,7 +547,7 @@ namespace ARMeilleure.Instructions { IOpCode32AluBf op = (IOpCode32AluBf)context.CurrOp; - var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. + int msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. Operand n = GetIntA32(context, op.Rn); Operand res = context.ShiftRightUI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb)); diff --git a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs index 55947c3b0..83d3e29a9 100644 --- a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs @@ -1,4 +1,5 @@ using ARMeilleure.CodeGen.Linking; +using ARMeilleure.Common; using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; @@ -205,7 +206,7 @@ namespace ARMeilleure.Instructions Operand hostAddress; - var table = context.FunctionTable; + IAddressTable table = context.FunctionTable; // If address is mapped onto the function table, we can skip the table walk. Otherwise we fallback // onto the dispatch stub. @@ -230,7 +231,7 @@ namespace ARMeilleure.Instructions for (int i = 0; i < table.Levels.Length; i++) { - var level = table.Levels[i]; + AddressTableLevel level = table.Levels[i]; int clearBits = 64 - (level.Index + level.Length); Operand index = context.ShiftLeft( diff --git a/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs b/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs index 150218827..ea9e33f26 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs @@ -143,8 +143,8 @@ namespace ARMeilleure.Instructions Operand address = context.Copy(GetIntA32(context, op.Rn)); - var exclusive = (accType & AccessType.Exclusive) != 0; - var ordered = (accType & AccessType.Ordered) != 0; + bool exclusive = (accType & AccessType.Exclusive) != 0; + bool ordered = (accType & AccessType.Ordered) != 0; if ((accType & AccessType.Load) != 0) { diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs index 1d68bce6b..6ec2b58f9 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs @@ -229,7 +229,7 @@ namespace ARMeilleure.Instructions private static Operand ZerosOrOnes(ArmEmitterContext context, Operand fromBool, OperandType baseType) { - var ones = (baseType == OperandType.I64) ? Const(-1L) : Const(-1); + Operand ones = (baseType == OperandType.I64) ? Const(-1L) : Const(-1); return context.ConditionalSelect(fromBool, ones, Const(baseType, 0L)); } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs index 9cfb90e3c..d42d5201b 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs @@ -118,15 +118,15 @@ namespace ARMeilleure.Instructions { OpCode32SimdCvtFFixed op = (OpCode32SimdCvtFFixed)context.CurrOp; - var toFixed = op.Opc == 1; + bool toFixed = op.Opc == 1; int fracBits = op.Fbits; - var unsigned = op.U; + bool unsigned = op.U; if (toFixed) // F32 to S32 or U32 (fixed) { EmitVectorUnaryOpF32(context, (op1) => { - var scaledValue = context.Multiply(op1, ConstF(MathF.Pow(2f, fracBits))); + Operand scaledValue = context.Multiply(op1, ConstF(MathF.Pow(2f, fracBits))); MethodInfo info = unsigned ? typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToU32)) : typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToS32)); return context.Call(info, scaledValue); @@ -136,7 +136,7 @@ namespace ARMeilleure.Instructions { EmitVectorUnaryOpI32(context, (op1) => { - var floatValue = unsigned ? context.ConvertToFPUI(OperandType.FP32, op1) : context.ConvertToFP(OperandType.FP32, op1); + Operand floatValue = unsigned ? context.ConvertToFPUI(OperandType.FP32, op1) : context.ConvertToFP(OperandType.FP32, op1); return context.Multiply(floatValue, ConstF(1f / MathF.Pow(2f, fracBits))); }, !unsigned); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs b/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs index 35c6dd328..3808ef929 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs @@ -87,7 +87,7 @@ namespace ARMeilleure.Instructions { if (op.Replicate) { - var regs = (count > 1) ? 1 : op.Increment; + int regs = (count > 1) ? 1 : op.Increment; for (int reg = 0; reg < regs; reg++) { int dreg = reg + d; diff --git a/src/ARMeilleure/Instructions/SoftFloat.cs b/src/ARMeilleure/Instructions/SoftFloat.cs index a51ff72bd..0f32cb7e1 100644 --- a/src/ARMeilleure/Instructions/SoftFloat.cs +++ b/src/ARMeilleure/Instructions/SoftFloat.cs @@ -1686,7 +1686,7 @@ namespace ARMeilleure.Instructions } else if (MathF.Abs(value) < MathF.Pow(2f, -128)) { - var overflowToInf = fpcr.GetRoundingMode() switch + bool overflowToInf = fpcr.GetRoundingMode() switch { FPRoundingMode.ToNearest => true, FPRoundingMode.TowardsPlusInfinity => !sign, @@ -3393,7 +3393,7 @@ namespace ARMeilleure.Instructions } else if (Math.Abs(value) < Math.Pow(2d, -1024)) { - var overflowToInf = fpcr.GetRoundingMode() switch + bool overflowToInf = fpcr.GetRoundingMode() switch { FPRoundingMode.ToNearest => true, FPRoundingMode.TowardsPlusInfinity => !sign, diff --git a/src/ARMeilleure/IntermediateRepresentation/Operand.cs b/src/ARMeilleure/IntermediateRepresentation/Operand.cs index 694638913..2b3545004 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Operand.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Operand.cs @@ -304,7 +304,7 @@ namespace ARMeilleure.IntermediateRepresentation ushort newCount = checked((ushort)(count + 1)); ushort newCapacity = (ushort)Math.Min(capacity * 2, ushort.MaxValue); - var oldSpan = new Span(data, count); + Span oldSpan = new(data, count); capacity = newCapacity; data = Allocators.References.Allocate(capacity); @@ -338,7 +338,7 @@ namespace ARMeilleure.IntermediateRepresentation throw new OverflowException(); } - var oldSpan = new Span(data, (int)count); + Span oldSpan = new(data, (int)count); capacity = newCapacity; data = Allocators.References.Allocate(capacity); @@ -352,7 +352,7 @@ namespace ARMeilleure.IntermediateRepresentation private static void Remove(in T item, ref T* data, ref ushort count) where T : unmanaged { - var span = new Span(data, count); + Span span = new(data, count); for (int i = 0; i < span.Length; i++) { @@ -372,7 +372,7 @@ namespace ARMeilleure.IntermediateRepresentation private static void Remove(in T item, ref T* data, ref uint count) where T : unmanaged { - var span = new Span(data, (int)count); + Span span = new(data, (int)count); for (int i = 0; i < span.Length; i++) { diff --git a/src/ARMeilleure/Signal/TestMethods.cs b/src/ARMeilleure/Signal/TestMethods.cs index f3c8d2c75..684157860 100644 --- a/src/ARMeilleure/Signal/TestMethods.cs +++ b/src/ARMeilleure/Signal/TestMethods.cs @@ -21,7 +21,7 @@ namespace ARMeilleure.Signal { EmitterContext context = new(); - var result = WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context); + Operand result = WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context); context.Return(result); @@ -38,7 +38,7 @@ namespace ARMeilleure.Signal { EmitterContext context = new(); - var result = WindowsPartialUnmapHandler.EmitThreadLocalMapIntGetOrReserve(context, structPtr, context.LoadArgument(OperandType.I32, 0), context.LoadArgument(OperandType.I32, 1)); + Operand result = WindowsPartialUnmapHandler.EmitThreadLocalMapIntGetOrReserve(context, structPtr, context.LoadArgument(OperandType.I32, 0), context.LoadArgument(OperandType.I32, 1)); context.Return(result); diff --git a/src/ARMeilleure/Translation/Cache/JitCache.cs b/src/ARMeilleure/Translation/Cache/JitCache.cs index db0a1268d..f0c1030a5 100644 --- a/src/ARMeilleure/Translation/Cache/JitCache.cs +++ b/src/ARMeilleure/Translation/Cache/JitCache.cs @@ -271,7 +271,7 @@ namespace ARMeilleure.Translation.Cache { entry = _cacheEntries[index]; - if (Optimizations.CacheEviction && _entryUsageStats.TryGetValue(offset, out var stats)) + if (Optimizations.CacheEviction && _entryUsageStats.TryGetValue(offset, out EntryUsageStats stats)) { stats.UpdateUsage(); } diff --git a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs index b07d9ffbb..15a1051fa 100644 --- a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs +++ b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs @@ -122,13 +122,13 @@ namespace ARMeilleure.Translation.Cache return null; // Not found. } - var unwindInfo = funcEntry.UnwindInfo; + CodeGen.Unwinding.UnwindInfo unwindInfo = funcEntry.UnwindInfo; int codeIndex = 0; for (int index = unwindInfo.PushEntries.Length - 1; index >= 0; index--) { - var entry = unwindInfo.PushEntries[index]; + UnwindPushEntry entry = unwindInfo.PushEntries[index]; switch (entry.PseudoOp) { diff --git a/src/ARMeilleure/Translation/ControlFlowGraph.cs b/src/ARMeilleure/Translation/ControlFlowGraph.cs index 45b092ec5..c9946d392 100644 --- a/src/ARMeilleure/Translation/ControlFlowGraph.cs +++ b/src/ARMeilleure/Translation/ControlFlowGraph.cs @@ -47,8 +47,8 @@ namespace ARMeilleure.Translation { RemoveUnreachableBlocks(Blocks); - var visited = new HashSet(); - var blockStack = new Stack(); + HashSet visited = new(); + Stack blockStack = new(); Array.Resize(ref _postOrderBlocks, Blocks.Count); Array.Resize(ref _postOrderMap, Blocks.Count); @@ -88,8 +88,8 @@ namespace ARMeilleure.Translation private void RemoveUnreachableBlocks(IntrusiveList blocks) { - var visited = new HashSet(); - var workQueue = new Queue(); + HashSet visited = new(); + Queue workQueue = new(); visited.Add(Entry); workQueue.Enqueue(Entry); diff --git a/src/ARMeilleure/Translation/PTC/Ptc.cs b/src/ARMeilleure/Translation/PTC/Ptc.cs index 5b02da124..2625a46df 100644 --- a/src/ARMeilleure/Translation/PTC/Ptc.cs +++ b/src/ARMeilleure/Translation/PTC/Ptc.cs @@ -10,6 +10,7 @@ using Ryujinx.Common.Logging; using Ryujinx.Common.Memory; using System; using System.Buffers.Binary; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -542,7 +543,7 @@ namespace ARMeilleure.Translation.PTC bool isEntryChanged = infoEntry.Hash != ComputeHash(translator.Memory, infoEntry.Address, infoEntry.GuestSize); - if (isEntryChanged || (!infoEntry.HighCq && Profiler.ProfiledFuncs.TryGetValue(infoEntry.Address, out var value) && value.HighCq)) + if (isEntryChanged || (!infoEntry.HighCq && Profiler.ProfiledFuncs.TryGetValue(infoEntry.Address, out PtcProfiler.FuncProfile value) && value.HighCq)) { infoEntry.Stubbed = true; infoEntry.CodeLength = 0; @@ -729,8 +730,8 @@ namespace ARMeilleure.Translation.PTC UnwindInfo unwindInfo, bool highCq) { - var cFunc = new CompiledFunction(code, unwindInfo, RelocInfo.Empty); - var gFunc = cFunc.MapWithPointer(out nint gFuncPointer); + CompiledFunction cFunc = new(code, unwindInfo, RelocInfo.Empty); + GuestFunction gFunc = cFunc.MapWithPointer(out nint gFuncPointer); return new TranslatedFunction(gFunc, gFuncPointer, callCounter, guestSize, highCq); } @@ -767,7 +768,7 @@ namespace ARMeilleure.Translation.PTC public void MakeAndSaveTranslations(Translator translator) { - var profiledFuncsToTranslate = Profiler.GetProfiledFuncsToTranslate(translator.Functions); + ConcurrentQueue<(ulong address, PtcProfiler.FuncProfile funcProfile)> profiledFuncsToTranslate = Profiler.GetProfiledFuncsToTranslate(translator.Functions); _translateCount = 0; _translateTotalCount = profiledFuncsToTranslate.Count; @@ -811,7 +812,7 @@ namespace ARMeilleure.Translation.PTC void TranslateFuncs() { - while (profiledFuncsToTranslate.TryDequeue(out var item)) + while (profiledFuncsToTranslate.TryDequeue(out (ulong address, PtcProfiler.FuncProfile funcProfile) item)) { ulong address = item.address; ExecutionMode executionMode = item.funcProfile.Mode; @@ -856,11 +857,11 @@ namespace ARMeilleure.Translation.PTC Stopwatch sw = Stopwatch.StartNew(); - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Start(); } - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Join(); } @@ -940,7 +941,7 @@ namespace ARMeilleure.Translation.PTC WriteCode(code.AsSpan()); // WriteReloc. - using var relocInfoWriter = new BinaryWriter(_relocsStream, EncodingCache.UTF8NoBOM, true); + using BinaryWriter relocInfoWriter = new(_relocsStream, EncodingCache.UTF8NoBOM, true); foreach (RelocEntry entry in relocInfo.Entries) { @@ -950,7 +951,7 @@ namespace ARMeilleure.Translation.PTC } // WriteUnwindInfo. - using var unwindInfoWriter = new BinaryWriter(_unwindInfosStream, EncodingCache.UTF8NoBOM, true); + using BinaryWriter unwindInfoWriter = new(_unwindInfosStream, EncodingCache.UTF8NoBOM, true); unwindInfoWriter.Write(unwindInfo.PushEntries.Length); diff --git a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs index 8ba600586..c46d81cf5 100644 --- a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs +++ b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs @@ -119,9 +119,9 @@ namespace ARMeilleure.Translation.PTC public ConcurrentQueue<(ulong address, FuncProfile funcProfile)> GetProfiledFuncsToTranslate(TranslatorCache funcs) { - var profiledFuncsToTranslate = new ConcurrentQueue<(ulong address, FuncProfile funcProfile)>(); + ConcurrentQueue<(ulong address, FuncProfile funcProfile)> profiledFuncsToTranslate = new(); - foreach (var profiledFunc in ProfiledFuncs) + foreach (KeyValuePair profiledFunc in ProfiledFuncs) { if (!funcs.ContainsKey(profiledFunc.Key) && !profiledFunc.Value.Blacklist) { @@ -142,7 +142,7 @@ namespace ARMeilleure.Translation.PTC { List funcs = []; - foreach (var profiledFunc in ProfiledFuncs) + foreach (KeyValuePair profiledFunc in ProfiledFuncs) { if (profiledFunc.Value.Blacklist) { diff --git a/src/ARMeilleure/Translation/SsaConstruction.cs b/src/ARMeilleure/Translation/SsaConstruction.cs index cddcfcd4f..e63cdc775 100644 --- a/src/ARMeilleure/Translation/SsaConstruction.cs +++ b/src/ARMeilleure/Translation/SsaConstruction.cs @@ -44,10 +44,10 @@ namespace ARMeilleure.Translation public static void Construct(ControlFlowGraph cfg) { - var globalDefs = new DefMap[cfg.Blocks.Count]; - var localDefs = new Operand[cfg.LocalsCount + RegisterConsts.TotalCount]; + DefMap[] globalDefs = new DefMap[cfg.Blocks.Count]; + Operand[] localDefs = new Operand[cfg.LocalsCount + RegisterConsts.TotalCount]; - var dfPhiBlocks = new Queue(); + Queue dfPhiBlocks = new(); for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) { diff --git a/src/ARMeilleure/Translation/Translator.cs b/src/ARMeilleure/Translation/Translator.cs index c2911829b..f96e71199 100644 --- a/src/ARMeilleure/Translation/Translator.cs +++ b/src/ARMeilleure/Translation/Translator.cs @@ -222,7 +222,7 @@ namespace ARMeilleure.Translation internal TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq, bool singleStep = false, bool pptcTranslation = false) { - var context = new ArmEmitterContext( + ArmEmitterContext context = new( Memory, CountTable, FunctionTable, @@ -265,10 +265,10 @@ namespace ARMeilleure.Translation Logger.EndPass(PassName.RegisterUsage); - var retType = OperandType.I64; - var argTypes = new OperandType[] { OperandType.I64 }; + OperandType retType = OperandType.I64; + OperandType[] argTypes = new OperandType[] { OperandType.I64 }; - var options = highCq ? CompilerOptions.HighCq : CompilerOptions.None; + CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None; if (context.HasPtc && !singleStep) { @@ -536,7 +536,7 @@ namespace ARMeilleure.Translation List functions = Functions.AsList(); - foreach (var func in functions) + foreach (TranslatedFunction func in functions) { JitCache.Unmap(func.FuncPointer); @@ -545,7 +545,7 @@ namespace ARMeilleure.Translation Functions.Clear(); - while (_oldFuncs.TryDequeue(out var kv)) + while (_oldFuncs.TryDequeue(out KeyValuePair kv)) { JitCache.Unmap(kv.Value.FuncPointer); @@ -566,7 +566,7 @@ namespace ARMeilleure.Translation { while (Queue.Count > 0 && Queue.TryDequeue(out RejitRequest request)) { - if (Functions.TryGetValue(request.Address, out var func) && func.CallCounter != null) + if (Functions.TryGetValue(request.Address, out TranslatedFunction func) && func.CallCounter != null) { Volatile.Write(ref func.CallCounter.Value, 0); } diff --git a/src/ARMeilleure/Translation/TranslatorStubs.cs b/src/ARMeilleure/Translation/TranslatorStubs.cs index e92573d33..cc6c67577 100644 --- a/src/ARMeilleure/Translation/TranslatorStubs.cs +++ b/src/ARMeilleure/Translation/TranslatorStubs.cs @@ -141,7 +141,7 @@ namespace ARMeilleure.Translation /// Generated private nint GenerateDispatchStub() { - var context = new EmitterContext(); + EmitterContext context = new(); Operand lblFallback = Label(); Operand lblEnd = Label(); @@ -160,7 +160,7 @@ namespace ARMeilleure.Translation for (int i = 0; i < _functionTable.Levels.Length; i++) { - ref var level = ref _functionTable.Levels[i]; + ref AddressTableLevel level = ref _functionTable.Levels[i]; // level.Mask is not used directly because it is more often bigger than 32-bits, so it will not // be encoded as an immediate on x86's bitwise and operation. @@ -184,11 +184,11 @@ namespace ARMeilleure.Translation hostAddress = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress)), guestAddress); context.Tailcall(hostAddress, nativeContext); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64 }; - var func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); + GuestFunction func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); return Marshal.GetFunctionPointerForDelegate(func); } @@ -199,7 +199,7 @@ namespace ARMeilleure.Translation /// Generated private nint GenerateSlowDispatchStub() { - var context = new EmitterContext(); + EmitterContext context = new(); // Load the target guest address from the native context. Operand nativeContext = context.LoadArgument(OperandType.I64, 0); @@ -209,11 +209,11 @@ namespace ARMeilleure.Translation Operand hostAddress = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress)), guestAddress); context.Tailcall(hostAddress, nativeContext); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64 }; - var func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); + GuestFunction func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); return Marshal.GetFunctionPointerForDelegate(func); } @@ -250,7 +250,7 @@ namespace ARMeilleure.Translation /// function private DispatcherFunction GenerateDispatchLoop() { - var context = new EmitterContext(); + EmitterContext context = new(); Operand beginLbl = Label(); Operand endLbl = Label(); @@ -286,9 +286,9 @@ namespace ARMeilleure.Translation context.Return(); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.None; - var argTypes = new[] { OperandType.I64, OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.None; + OperandType[] argTypes = new[] { OperandType.I64, OperandType.I64 }; return Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); } @@ -299,7 +299,7 @@ namespace ARMeilleure.Translation /// function private WrapperFunction GenerateContextWrapper() { - var context = new EmitterContext(); + EmitterContext context = new(); Operand nativeContext = context.LoadArgument(OperandType.I64, 0); Operand guestMethod = context.LoadArgument(OperandType.I64, 1); @@ -310,9 +310,9 @@ namespace ARMeilleure.Translation context.Return(returnValue); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64, OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64, OperandType.I64 }; return Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); } diff --git a/src/LibKenjinx/Android/Interop.cs b/src/LibKenjinx/Android/Interop.cs index b5abe0194..6b01a4c18 100644 --- a/src/LibKenjinx/Android/Interop.cs +++ b/src/LibKenjinx/Android/Interop.cs @@ -32,10 +32,10 @@ namespace LibKenjinx.Android internal static void Initialize(JEnvRef jniEnv) { - var vm = JniHelper.GetVirtualMachine(jniEnv); + JavaVMRef? vm = JniHelper.GetVirtualMachine(jniEnv); if (_classId == null) { - var className = new ReadOnlySpan(Encoding.UTF8.GetBytes(BaseClassName)); + ReadOnlySpan className = new(Encoding.UTF8.GetBytes(BaseClassName)); using (IReadOnlyFixedMemory.IDisposable cName = className.GetUnsafeValPtr() .GetUnsafeFixedContext(className.Length)) { @@ -48,7 +48,7 @@ namespace LibKenjinx.Android } } - foreach (var x in _methods) + foreach ((string name, string descriptor) x in _methods) { CacheMethod(jniEnv, x.name, x.descriptor); } @@ -58,10 +58,10 @@ namespace LibKenjinx.Android private static void CacheMethod(JEnvRef jEnv, string name, string descriptor) { - if (!_methodCache.TryGetValue((name, descriptor), out var method)) + if (!_methodCache.TryGetValue((name, descriptor), out JMethodId method)) { - var methodName = new ReadOnlySpan(Encoding.UTF8.GetBytes(name)); - var descriptorId = new ReadOnlySpan(Encoding.UTF8.GetBytes(descriptor)); + ReadOnlySpan methodName = new(Encoding.UTF8.GetBytes(name)); + ReadOnlySpan descriptorId = new(Encoding.UTF8.GetBytes(descriptor)); using (IReadOnlyFixedMemory.IDisposable mName = methodName.GetUnsafeValPtr() .GetUnsafeFixedContext(methodName.Length)) using (IReadOnlyFixedMemory.IDisposable dName = descriptorId.GetUnsafeValPtr() @@ -69,7 +69,7 @@ namespace LibKenjinx.Android { if (_classId != null) { - var methodId = JniHelper.GetStaticMethodId(jEnv, (JClassLocalRef)(_classId.Value.Value), mName, dName); + JMethodId? methodId = JniHelper.GetStaticMethodId(jEnv, (JClassLocalRef)(_classId.Value.Value), mName, dName); if (methodId == null) { Logger.Warning?.Print(LogClass.Application, $"Java Method Id {name} not found"); @@ -86,8 +86,8 @@ namespace LibKenjinx.Android private static void CallVoidMethod(string name, string descriptor, params JValue[] values) { - using var env = JniEnv.Create(); - if (_methodCache.TryGetValue((name, descriptor), out var method)) + using JniEnv? env = JniEnv.Create(); + if (_methodCache.TryGetValue((name, descriptor), out JMethodId method)) { if (descriptor.EndsWith("V")) { @@ -101,8 +101,8 @@ namespace LibKenjinx.Android private static JLong CallLongMethod(string name, string descriptor, params JValue[] values) { - using var env = JniEnv.Create(); - if (_methodCache.TryGetValue((name, descriptor), out var method)) + using JniEnv? env = JniEnv.Create(); + if (_methodCache.TryGetValue((name, descriptor), out JMethodId method)) { if (descriptor.EndsWith("J")) if (env != null && _classId != null) @@ -127,7 +127,7 @@ namespace LibKenjinx.Android public static void UpdateProgress(string info, float progress) { - using var infoPtr = new TempNativeString(info); + using TempNativeString infoPtr = new(info); CallVoidMethod("updateProgress", "(JF)V", JValue.Create(infoPtr.AsBytes()), JValue.Create(progress.AsBytes())); @@ -153,11 +153,11 @@ namespace LibKenjinx.Android string newSubtitle, string newInitialText) { - using var titlePointer = new TempNativeString(newTitle); - using var messagePointer = new TempNativeString(newMessage); - using var watermarkPointer = new TempNativeString(newWatermark); - using var subtitlePointer = new TempNativeString(newSubtitle); - using var newInitialPointer = new TempNativeString(newInitialText); + using TempNativeString titlePointer = new(newTitle); + using TempNativeString messagePointer = new(newMessage); + using TempNativeString watermarkPointer = new(newWatermark); + using TempNativeString subtitlePointer = new(newSubtitle); + using TempNativeString newInitialPointer = new(newInitialText); CallVoidMethod("updateUiHandler", "(JJJIIIIJJ)V", JValue.Create(titlePointer.AsBytes()), JValue.Create(messagePointer.AsBytes()), @@ -224,7 +224,7 @@ namespace LibKenjinx.Android { bool newAttach = false; ReadOnlySpan threadName = "JvmCall"u8; - var env = _jvm == null ? default : JniHelper.Attach(_jvm.Value, threadName.GetUnsafeValPtr().GetUnsafeFixedContext(threadName.Length), + JEnvRef? env = _jvm == null ? default : JniHelper.Attach(_jvm.Value, threadName.GetUnsafeValPtr().GetUnsafeFixedContext(threadName.Length), out newAttach); return env != null ? new JniEnv(env.Value, newAttach) : null; diff --git a/src/LibKenjinx/Android/JniExportedMethods.cs b/src/LibKenjinx/Android/JniExportedMethods.cs index 7bb982cb4..e20820ebd 100644 --- a/src/LibKenjinx/Android/JniExportedMethods.cs +++ b/src/LibKenjinx/Android/JniExportedMethods.cs @@ -1,6 +1,7 @@ using LibKenjinx.Android; using LibKenjinx.Jni.Pointers; using Ryujinx.Audio.Backends.OpenAL; +using Ryujinx.Audio.Integration; using Ryujinx.Common; using Ryujinx.Common.Configuration; using Ryujinx.Common.Logging; @@ -17,6 +18,8 @@ using System.Linq; using System.Numerics; using System.Runtime.InteropServices; using Ryujinx.Graphics.Vulkan; +using System.IO; +using System.Reflection; namespace LibKenjinx { @@ -64,10 +67,10 @@ namespace LibKenjinx private static bool TryCallBool(object? target, string[] names, bool arg) { if (target == null) return false; - var t = target.GetType(); - foreach (var name in names) + Type t = target.GetType(); + foreach (string name in names) { - var m = t.GetMethod(name, new[] { typeof(bool) }); + MethodInfo? m = t.GetMethod(name, new[] { typeof(bool) }); if (m != null) { try { m.Invoke(target, new object[] { arg }); return true; } catch { } @@ -80,10 +83,10 @@ namespace LibKenjinx private static bool TryCallFloat(object? target, string[] names, float arg) { if (target == null) return false; - var t = target.GetType(); - foreach (var name in names) + Type t = target.GetType(); + foreach (string name in names) { - var m = t.GetMethod(name, new[] { typeof(float) }); + MethodInfo? m = t.GetMethod(name, new[] { typeof(float) }); if (m != null) { try { m.Invoke(target, new object[] { arg }); return true; } catch { } @@ -96,10 +99,10 @@ namespace LibKenjinx private static bool TrySetFloatProp(object? target, string[] names, float value) { if (target == null) return false; - var t = target.GetType(); - foreach (var name in names) + Type t = target.GetType(); + foreach (string name in names) { - var p = t.GetProperty(name); + PropertyInfo? p = t.GetProperty(name); if (p != null && p.CanWrite) { try @@ -119,10 +122,10 @@ namespace LibKenjinx private static bool TrySetBoolProp(object target, params string[] names) { if (target == null) return false; - var t = target.GetType(); - foreach (var name in names) + Type t = target.GetType(); + foreach (string name in names) { - var p = t.GetProperty(name); + PropertyInfo? p = t.GetProperty(name); if (p != null && p.CanWrite && p.PropertyType == typeof(bool)) { try { p.SetValue(target, true); return true; } catch { } @@ -138,9 +141,9 @@ namespace LibKenjinx yield return root; - var t = root.GetType(); - var props = t.GetProperties(); - foreach (var p in props) + Type t = root.GetType(); + PropertyInfo[] props = t.GetProperties(); + foreach (PropertyInfo p in props) { object? val = null; try { val = p.GetValue(root); } catch { /* ignore */ } @@ -154,7 +157,7 @@ namespace LibKenjinx p.Name.IndexOf("Output", StringComparison.OrdinalIgnoreCase) >= 0 || p.PropertyType.Name.IndexOf("Audio", StringComparison.OrdinalIgnoreCase) >= 0) { - foreach (var x in WalkAudioObjects(val, depth - 1)) + foreach (object? x in WalkAudioObjects(val, depth - 1)) yield return x; } } @@ -171,26 +174,26 @@ namespace LibKenjinx try { // 1) Try SwitchDevice wrapper itself - var dev = SwitchDevice; + SwitchDevice? dev = SwitchDevice; if (dev != null && TryCallBool(dev, PauseMethodCandidates, pause)) hits++; // 2) Try underlying Switch or similar inner object - var inner = + object? inner = dev?.GetType().GetProperty("Switch")?.GetValue(dev) ?? dev?.GetType().GetProperty("Device")?.GetValue(dev); if (inner != null && TryCallBool(inner, PauseMethodCandidates, pause)) hits++; // 3) Try EmulationContext and its "System" (kernel/front controller etc.) - var ctx = dev?.EmulationContext; + Switch? ctx = dev?.EmulationContext; if (ctx != null) { if (TryCallBool(ctx, PauseMethodCandidates, pause)) hits++; - var sys = ctx.GetType().GetProperty("System")?.GetValue(ctx); + object? sys = ctx.GetType().GetProperty("System")?.GetValue(ctx); if (sys != null && TryCallBool(sys, PauseMethodCandidates, pause)) hits++; // 4) walk all audio-ish descendants and try pause - foreach (var node in WalkAudioObjects(ctx, depth: 2)) + foreach (object? node in WalkAudioObjects(ctx, depth: 2)) { if (node != null && TryCallBool(node, PauseMethodCandidates, pause)) hits++; @@ -218,7 +221,7 @@ namespace LibKenjinx // A) Direct: OpenAL driver (if used) try { - var oal = _openAl; + OpenALHardwareDeviceDriver? oal = _openAl; if (oal != null) { bool p = TryCallBool(oal, PauseMethodCandidates, _audioPaused); @@ -231,10 +234,10 @@ namespace LibKenjinx // B) EmulationContext managers (AudioRendererManager/AudioManager/AudioOutManager/…) try { - var ctx = SwitchDevice?.EmulationContext; + Switch? ctx = SwitchDevice?.EmulationContext; if (ctx != null) { - foreach (var node in WalkAudioObjects(ctx, depth: 2)) + foreach (object? node in WalkAudioObjects(ctx, depth: 2)) { if (node == null) continue; @@ -254,7 +257,7 @@ namespace LibKenjinx // C) Generic driver fallback (whatever AudioDriver actually is) try { - var drv = AudioDriver; + IHardwareDeviceDriver? drv = AudioDriver; if (drv != null) { bool p = TryCallBool(drv, PauseMethodCandidates, _audioPaused); @@ -307,9 +310,9 @@ namespace LibKenjinx AsyncLogTargetOverflowAction.Block )); - var path = Marshal.PtrToStringAnsi(jpathId); + string? path = Marshal.PtrToStringAnsi(jpathId); - var init = Initialize(path); + bool init = Initialize(path); Interop.Initialize(new JEnvRef(jniEnv)); @@ -347,7 +350,7 @@ namespace LibKenjinx AudioDriver = new OpenALHardwareDeviceDriver(); _openAl = AudioDriver as OpenALHardwareDeviceDriver; // <-- audio patch: keep a strong ref - var timezone = Marshal.PtrToStringAnsi(timeZonePtr); + string? timezone = Marshal.PtrToStringAnsi(timeZonePtr); return InitializeDevice((MemoryManagerMode)memoryManagerMode, useNce, (MemoryConfiguration)memoryConfiguration, @@ -369,7 +372,7 @@ namespace LibKenjinx public static double JnaGetGameFifo() { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var stats = SwitchDevice?.EmulationContext?.Statistics.GetFifoPercent() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetFifoPercent() ?? 0; return stats; } @@ -378,7 +381,7 @@ namespace LibKenjinx public static double JnaGetGameFrameTime() { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameTime() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameTime() ?? 0; return stats; } @@ -387,7 +390,7 @@ namespace LibKenjinx public static double JnaGetGameFrameRate() { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameRate() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameRate() ?? 0; return stats; } @@ -408,7 +411,7 @@ namespace LibKenjinx public static nint JniGetDlcContentListNative(nint pathPtr, long titleId) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var list = GetDlcContentList(Marshal.PtrToStringAnsi(pathPtr) ?? "", (ulong)titleId); + List list = GetDlcContentList(Marshal.PtrToStringAnsi(pathPtr) ?? "", (ulong)titleId); return CreateStringArray(list); } @@ -450,8 +453,8 @@ namespace LibKenjinx return false; } - var stream = OpenFile(descriptor); - var update = updateDescriptor == -1 ? null : OpenFile(updateDescriptor); + FileStream stream = OpenFile(descriptor); + FileStream? update = updateDescriptor == -1 ? null : OpenFile(updateDescriptor); return LoadApplication(stream, (FileType)type, update); } @@ -461,7 +464,7 @@ namespace LibKenjinx { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var stream = OpenFile(descriptor); + FileStream stream = OpenFile(descriptor); nint stringHandle = 0; string? version = "0.0"; @@ -488,7 +491,7 @@ namespace LibKenjinx { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var stream = OpenFile(descriptor); + FileStream stream = OpenFile(descriptor); InstallFirmware(stream, isXci); } @@ -498,7 +501,7 @@ namespace LibKenjinx { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var version = GetInstalledFirmwareVersion() ?? "0.0"; + string version = GetInstalledFirmwareVersion() ?? "0.0"; return Marshal.StringToHGlobalAnsi(version); } @@ -557,16 +560,16 @@ namespace LibKenjinx _surfacePtr = Interop.GetSurfacePtr(); _window = Interop.GetWindowsHandle(); - var api = VulkanLoader?.GetApi() ?? Vk.GetApi(); + Vk? api = VulkanLoader?.GetApi() ?? Vk.GetApi(); if (api.TryGetInstanceExtension(new Instance(instance), out KhrAndroidSurface surfaceExtension)) { - var createInfo = new AndroidSurfaceCreateInfoKHR + AndroidSurfaceCreateInfoKHR createInfo = new() { SType = StructureType.AndroidSurfaceCreateInfoKhr, Window = (nint*)_surfacePtr, }; - var result = surfaceExtension.CreateAndroidSurface(new Instance(instance), in createInfo, null, out var surface); + Result result = surfaceExtension.CreateAndroidSurface(new Instance(instance), in createInfo, null, out SurfaceKHR* surface); // If a rotation was applied before the surface was created → apply it now if (_window != 0 && _pendingRotationDegrees != -1) @@ -618,7 +621,7 @@ namespace LibKenjinx { if (SwitchDevice?.EmulationContext != null) { - var time = SwitchDevice.EmulationContext.Statistics.GetGameFrameTime(); + double time = SwitchDevice.EmulationContext.Statistics.GetGameFrameTime(); Interop.FrameEnded(time); } }); @@ -641,11 +644,11 @@ namespace LibKenjinx public unsafe static void JniGetGameInfo(int fileDescriptor, nint extension, nint infoPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - using var stream = OpenFile(fileDescriptor); - var ext = Marshal.PtrToStringAnsi(extension); - var info = GetGameInfo(stream, ext?.ToLower() ?? string.Empty) ?? GetDefaultInfo(stream); - var i = (GameInfoNative*)infoPtr; - var n = new GameInfoNative(info); + using FileStream stream = OpenFile(fileDescriptor); + string? ext = Marshal.PtrToStringAnsi(extension); + GameInfo info = GetGameInfo(stream, ext?.ToLower() ?? string.Empty) ?? GetDefaultInfo(stream); + GameInfoNative* i = (GameInfoNative*)infoPtr; + GameInfoNative n = new(info); i->TitleId = n.TitleId; i->TitleName = n.TitleName; i->Version = n.Version; @@ -714,14 +717,14 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "inputSetAccelerometerData")] public static void JniSetAccelerometerData(float x, float y, float z, int id) { - var accel = new Vector3(x, y, z); + Vector3 accel = new(x, y, z); SetAccelerometerData(accel, id); } [UnmanagedCallersOnly(EntryPoint = "inputSetGyroData")] public static void JniSetGyroData(float x, float y, float z, int id) { - var gryo = new Vector3(x, y, z); + Vector3 gryo = new(x, y, z); SetGryoData(gryo, id); } @@ -743,8 +746,8 @@ namespace LibKenjinx public static nint JniGetOpenedUser() { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = GetOpenedUser(); - var ptr = Marshal.StringToHGlobalAnsi(userId); + string userId = GetOpenedUser(); + IntPtr ptr = Marshal.StringToHGlobalAnsi(userId); return ptr; } @@ -753,7 +756,7 @@ namespace LibKenjinx public static nint JniGetUserPicture(nint userIdPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; return Marshal.StringToHGlobalAnsi(GetUserPicture(userId)); } @@ -762,8 +765,8 @@ namespace LibKenjinx public static void JniGetUserPicture(nint userIdPtr, nint picturePtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; - var picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; SetUserPicture(userId, picture); } @@ -772,7 +775,7 @@ namespace LibKenjinx public static nint JniGetUserName(nint userIdPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; return Marshal.StringToHGlobalAnsi(GetUserName(userId)); } @@ -781,8 +784,8 @@ namespace LibKenjinx public static void JniSetUserName(nint userIdPtr, nint userNamePtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; - var userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; SetUserName(userId, userName); } @@ -791,7 +794,7 @@ namespace LibKenjinx public static nint JniGetAllUsers() { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var users = GetAllUsers(); + string[] users = GetAllUsers(); return CreateStringArray(users.ToList()); } @@ -800,8 +803,8 @@ namespace LibKenjinx public static void JniAddUser(nint userNamePtr, nint picturePtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; - var picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; + string userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; + string picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; AddUser(userName, picture); } @@ -810,7 +813,7 @@ namespace LibKenjinx public static void JniDeleteUser(nint userIdPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; DeleteUser(userId); } @@ -847,7 +850,7 @@ namespace LibKenjinx public static void JniOpenUser(nint userIdPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; OpenUser(userId); } @@ -856,7 +859,7 @@ namespace LibKenjinx public static void JniCloseUser(nint userIdPtr) { Logger.Trace?.Print(LogClass.Application, "Jni Function Call"); - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; CloseUser(userId); } diff --git a/src/LibKenjinx/LibKenjinx.Device.cs b/src/LibKenjinx/LibKenjinx.Device.cs index 6580d0d84..243c80049 100644 --- a/src/LibKenjinx/LibKenjinx.Device.cs +++ b/src/LibKenjinx/LibKenjinx.Device.cs @@ -59,7 +59,7 @@ namespace LibKenjinx public static string GetInstalledFirmwareVersion() { - var version = SwitchDevice?.ContentManager?.GetCurrentFirmwareVersion(); + SystemVersion? version = SwitchDevice?.ContentManager?.GetCurrentFirmwareVersion(); if (version != null) { @@ -76,7 +76,7 @@ namespace LibKenjinx public static bool LoadApplication(Stream stream, FileType type, Stream? updateStream = null) { - var emulationContext = SwitchDevice?.EmulationContext; + Switch? emulationContext = SwitchDevice?.EmulationContext; return type switch { @@ -97,7 +97,7 @@ namespace LibKenjinx public static bool LoadApplication(string? path) { - var emulationContext = SwitchDevice?.EmulationContext; + Switch? emulationContext = SwitchDevice?.EmulationContext; if (Directory.Exists(path)) { @@ -249,7 +249,7 @@ namespace LibKenjinx private static FileStream OpenFile(int descriptor) { - var safeHandle = new SafeFileHandle(descriptor, false); + SafeFileHandle safeHandle = new(descriptor, false); return new FileStream(safeHandle, FileAccess.ReadWrite); } diff --git a/src/LibKenjinx/LibKenjinx.Graphics.cs b/src/LibKenjinx/LibKenjinx.Graphics.cs index 7f0e1d14e..18afc6bbc 100644 --- a/src/LibKenjinx/LibKenjinx.Graphics.cs +++ b/src/LibKenjinx/LibKenjinx.Graphics.cs @@ -8,6 +8,7 @@ using Ryujinx.Graphics.Gpu; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.OpenGL; using Ryujinx.Graphics.Vulkan; +using Ryujinx.HLE; using Silk.NET.Vulkan; using System; using System.Runtime.InteropServices; @@ -62,7 +63,7 @@ namespace LibKenjinx else if (graphicsBackend == GraphicsBackend.Vulkan) { // Prefer the platform-provided Vulkan loader (if present), fall back to default. - var api = VulkanLoader?.GetApi() ?? Vk.GetApi(); + Vk? api = VulkanLoader?.GetApi() ?? Vk.GetApi(); Renderer = new VulkanRenderer( api, @@ -89,7 +90,7 @@ namespace LibKenjinx public static void SetVsyncState(Ryujinx.Common.Configuration.VSyncMode vSyncMode) { - var device = SwitchDevice!.EmulationContext!; + Switch device = SwitchDevice!.EmulationContext!; device.VSyncMode = vSyncMode; device.Gpu.Renderer.Window.ChangeVSyncMode((Ryujinx.Graphics.GAL.VSyncMode)vSyncMode); } @@ -103,7 +104,7 @@ namespace LibKenjinx ARMeilleure.Optimizations.EcoFriendly = SwitchDevice!.EnableLowPowerPtc; ARMeilleure.Optimizations.CacheEviction = SwitchDevice.EnableJitCacheEviction; - var device = SwitchDevice.EmulationContext!; + Switch device = SwitchDevice.EmulationContext!; _gpuDoneEvent = new ManualResetEvent(true); device.Gpu.Renderer.Initialize(_enableGraphicsLogging ? GraphicsDebugLevel.All : GraphicsDebugLevel.None); @@ -179,8 +180,8 @@ namespace LibKenjinx Interop.UpdateProgress(status, value); } } - var status = $"{current} / {total}"; - var progress = current / (float)total; + string status = $"{current} / {total}"; + float progress = current / (float)total; if (float.IsNaN(progress)) progress = 0; diff --git a/src/LibKenjinx/LibKenjinx.Input.cs b/src/LibKenjinx/LibKenjinx.Input.cs index ba77de4b2..ed9a5829e 100644 --- a/src/LibKenjinx/LibKenjinx.Input.cs +++ b/src/LibKenjinx/LibKenjinx.Input.cs @@ -92,10 +92,10 @@ namespace LibKenjinx public static int ConnectGamepad(int index) { - var gamepad = _gamepadDriver?.GetGamepad(index); + IGamepad? gamepad = _gamepadDriver?.GetGamepad(index); if (gamepad != null) { - var config = CreateDefaultInputConfig(); + InputConfig config = CreateDefaultInputConfig(); config.Id = gamepad.Id; config.PlayerIndex = (PlayerIndex)index; @@ -105,7 +105,7 @@ namespace LibKenjinx _npadManager?.ReloadConfiguration(_configs.Where(x => x != null).ToList(), false, false); - return int.TryParse(gamepad?.Id, out var idInt) ? idInt : -1; + return int.TryParse(gamepad?.Id, out int idInt) ? idInt : -1; } private static InputConfig CreateDefaultInputConfig() @@ -356,7 +356,7 @@ namespace LibKenjinx if (disposing) { // Simulate a full disconnect when disposing - var ids = GamepadsIds; + ReadOnlySpan ids = GamepadsIds; foreach (string id in ids) { OnGamepadDisconnected?.Invoke(id); @@ -381,7 +381,7 @@ namespace LibKenjinx public void SetStickAxis(StickInputId stick, Vector2 axes, int deviceId) { - if(_gamePads.TryGetValue(deviceId, out var gamePad)) + if(_gamePads.TryGetValue(deviceId, out VirtualGamepad? gamePad)) { gamePad.StickInputs[(int)stick] = axes; } @@ -389,7 +389,7 @@ namespace LibKenjinx public void SetButtonPressed(GamepadButtonInputId button, int deviceId) { - if (_gamePads.TryGetValue(deviceId, out var gamePad)) + if (_gamePads.TryGetValue(deviceId, out VirtualGamepad? gamePad)) { gamePad.ButtonInputs[(int)button] = true; } @@ -397,7 +397,7 @@ namespace LibKenjinx public void SetButtonReleased(GamepadButtonInputId button, int deviceId) { - if (_gamePads.TryGetValue(deviceId, out var gamePad)) + if (_gamePads.TryGetValue(deviceId, out VirtualGamepad? gamePad)) { gamePad.ButtonInputs[(int)button] = false; } @@ -405,7 +405,7 @@ namespace LibKenjinx public void SetAccelerometerData(Vector3 accel, int deviceId) { - if (_gamePads.TryGetValue(deviceId, out var gamePad)) + if (_gamePads.TryGetValue(deviceId, out VirtualGamepad? gamePad)) { gamePad.Accelerometer = accel; } @@ -413,7 +413,7 @@ namespace LibKenjinx public void SetGryoData(Vector3 gyro, int deviceId) { - if (_gamePads.TryGetValue(deviceId, out var gamePad)) + if (_gamePads.TryGetValue(deviceId, out VirtualGamepad? gamePad)) { gamePad.Gyro = gyro; } @@ -458,7 +458,7 @@ namespace LibKenjinx public (float, float) GetStick(StickInputId inputId) { - var v = _stickInputs[(int)inputId]; + Vector2 v = _stickInputs[(int)inputId]; return (v.X, v.Y); } @@ -496,7 +496,7 @@ namespace LibKenjinx { GamepadStateSnapshot result = default; - foreach (var button in Enum.GetValues()) + foreach (GamepadButtonInputId button in Enum.GetValues()) { // Do not touch state of button already pressed if (button != GamepadButtonInputId.Count && !result.IsPressed(button)) diff --git a/src/LibKenjinx/LibKenjinx.Native.cs b/src/LibKenjinx/LibKenjinx.Native.cs index 919039906..97582b613 100644 --- a/src/LibKenjinx/LibKenjinx.Native.cs +++ b/src/LibKenjinx/LibKenjinx.Native.cs @@ -8,6 +8,7 @@ using Ryujinx.HLE.HOS.SystemState; using Ryujinx.Input; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; @@ -66,7 +67,7 @@ namespace LibKenjinx return false; } - var path = Marshal.PtrToStringAnsi(pathPtr); + string? path = Marshal.PtrToStringAnsi(pathPtr); return LoadApplication(path); } @@ -74,7 +75,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_install_firmware")] public static void InstallFirmwareNative(int descriptor, bool isXci) { - var stream = OpenFile(descriptor); + FileStream stream = OpenFile(descriptor); InstallFirmware(stream, isXci); } @@ -82,16 +83,16 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_installed_firmware_version")] public static nint GetInstalledFirmwareVersionNative() { - var result = GetInstalledFirmwareVersion(); + string result = GetInstalledFirmwareVersion(); return Marshal.StringToHGlobalAnsi(result); } [UnmanagedCallersOnly(EntryPoint = "initialize")] public static bool InitializeNative(nint basePathPtr) { - var path = Marshal.PtrToStringAnsi(basePathPtr); + string? path = Marshal.PtrToStringAnsi(basePathPtr); - var res = Initialize(path); + bool res = Initialize(path); InitializeAudio(); @@ -119,10 +120,10 @@ namespace LibKenjinx } List extensions = []; - var extPtr = (nint*)nativeGraphicsInterop.VkRequiredExtensions; + IntPtr* extPtr = (nint*)nativeGraphicsInterop.VkRequiredExtensions; for (int i = 0; i < nativeGraphicsInterop.VkRequiredExtensionsCount; i++) { - var ptr = extPtr[i]; + IntPtr ptr = extPtr[i]; extensions.Add(Marshal.PtrToStringAnsi(ptr) ?? string.Empty); } @@ -142,7 +143,7 @@ namespace LibKenjinx { if (Renderer is OpenGLRenderer) { - var proc = Marshal.GetDelegateForFunctionPointer(_nativeGraphicsInterop.GlGetProcAddress); + GetProcAddress proc = Marshal.GetDelegateForFunctionPointer(_nativeGraphicsInterop.GlGetProcAddress); GL.LoadBindings(new OpenTKBindingsContext(x => proc.Invoke(x))); } RunLoop(); @@ -163,10 +164,10 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "get_game_info")] public static GameInfoNative GetGameInfoNative(int descriptor, nint extensionPtr) { - var extension = Marshal.PtrToStringAnsi(extensionPtr); - var stream = OpenFile(descriptor); + string? extension = Marshal.PtrToStringAnsi(extensionPtr); + FileStream stream = OpenFile(descriptor); - var gameInfo = GetGameInfo(stream, extension ?? ""); + GameInfo? gameInfo = GetGameInfo(stream, extension ?? ""); return gameInfo == null ? default : new GameInfoNative(gameInfo.FileSize, gameInfo.TitleName, gameInfo.TitleId, gameInfo.Developer, gameInfo.Version, gameInfo.Icon); } @@ -240,7 +241,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_game_fifo")] public static double GetGameInfoNative() { - var stats = SwitchDevice?.EmulationContext?.Statistics.GetFifoPercent() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetFifoPercent() ?? 0; return stats; } @@ -248,7 +249,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_game_frame_time")] public static double GetGameFrameTimeNative() { - var stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameTime() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameTime() ?? 0; return stats; } @@ -256,7 +257,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_game_frame_rate")] public static double GetGameFrameRateNative() { - var stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameRate() ?? 0; + double stats = SwitchDevice?.EmulationContext?.Statistics.GetGameFrameRate() ?? 0; return stats; } @@ -275,7 +276,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_dlc_content_list")] public static nint GetDlcContentListNative(nint pathPtr, long titleId) { - var list = GetDlcContentList(Marshal.PtrToStringAnsi(pathPtr) ?? "", (ulong)titleId); + List list = GetDlcContentList(Marshal.PtrToStringAnsi(pathPtr) ?? "", (ulong)titleId); return CreateStringArray(list); } @@ -312,8 +313,8 @@ namespace LibKenjinx return false; } - var stream = OpenFile(descriptor); - var update = updateDescriptor == -1 ? null : OpenFile(updateDescriptor); + FileStream stream = OpenFile(descriptor); + FileStream? update = updateDescriptor == -1 ? null : OpenFile(updateDescriptor); return LoadApplication(stream, (FileType)type, update); } @@ -321,7 +322,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_verify_firmware")] public static nint VerifyFirmwareNative(int descriptor, bool isXci) { - var stream = OpenFile(descriptor); + FileStream stream = OpenFile(descriptor); nint stringHandle = 0; string? version = "0.0"; @@ -358,11 +359,11 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "device_get_game_info")] public unsafe static void GetGameInfoNative(int fileDescriptor, nint extension, nint infoPtr) { - using var stream = OpenFile(fileDescriptor); - var ext = Marshal.PtrToStringAnsi(extension); - var info = GetGameInfo(stream, ext?.ToLower() ?? string.Empty) ?? GetDefaultInfo(stream); - var i = (GameInfoNative*)infoPtr; - var n = new GameInfoNative(info); + using FileStream stream = OpenFile(fileDescriptor); + string? ext = Marshal.PtrToStringAnsi(extension); + GameInfo info = GetGameInfo(stream, ext?.ToLower() ?? string.Empty) ?? GetDefaultInfo(stream); + GameInfoNative* i = (GameInfoNative*)infoPtr; + GameInfoNative n = new(info); i->TitleId = n.TitleId; i->TitleName = n.TitleName; i->Version = n.Version; @@ -375,8 +376,8 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_get_opened_user")] public static nint GetOpenedUserNative() { - var userId = GetOpenedUser(); - var ptr = Marshal.StringToHGlobalAnsi(userId); + string userId = GetOpenedUser(); + IntPtr ptr = Marshal.StringToHGlobalAnsi(userId); return ptr; } @@ -384,7 +385,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_get_user_picture")] public static nint GetUserPictureNative(nint userIdPtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; return Marshal.StringToHGlobalAnsi(GetUserPicture(userId)); } @@ -392,8 +393,8 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_set_user_picture")] public static void SetUserPictureNative(nint userIdPtr, nint picturePtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; - var picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; SetUserPicture(userId, picture); } @@ -401,7 +402,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_get_user_name")] public static nint GetUserNameNative(nint userIdPtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; return Marshal.StringToHGlobalAnsi(GetUserName(userId)); } @@ -409,8 +410,8 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_set_user_name")] public static void SetUserNameNative(nint userIdPtr, nint userNamePtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; - var userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; SetUserName(userId, userName); } @@ -418,7 +419,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_get_all_users")] public static nint GetAllUsersNative() { - var users = GetAllUsers(); + string[] users = GetAllUsers(); return CreateStringArray(users.ToList()); } @@ -426,8 +427,8 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_add_user")] public static void AddUserNative(nint userNamePtr, nint picturePtr) { - var userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; - var picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; + string userName = Marshal.PtrToStringAnsi(userNamePtr) ?? ""; + string picture = Marshal.PtrToStringAnsi(picturePtr) ?? ""; AddUser(userName, picture); } @@ -435,7 +436,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_delete_user")] public static void DeleteUserNative(nint userIdPtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; DeleteUser(userId); } @@ -443,7 +444,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_open_user")] public static void OpenUserNative(nint userIdPtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; OpenUser(userId); } @@ -451,7 +452,7 @@ namespace LibKenjinx [UnmanagedCallersOnly(EntryPoint = "user_close_user")] public static void CloseUserNative(nint userIdPtr) { - var userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; + string userId = Marshal.PtrToStringAnsi(userIdPtr) ?? ""; CloseUser(userId); } diff --git a/src/LibKenjinx/LibKenjinx.NativeHelpers.cs b/src/LibKenjinx/LibKenjinx.NativeHelpers.cs index 6c041b49d..9a61c5bbb 100644 --- a/src/LibKenjinx/LibKenjinx.NativeHelpers.cs +++ b/src/LibKenjinx/LibKenjinx.NativeHelpers.cs @@ -1,4 +1,5 @@ using Ryujinx.Common.Configuration; +using Ryujinx.HLE; using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ namespace LibKenjinx private unsafe static nint CreateStringArray(List strings) { uint size = (uint)(Marshal.SizeOf() * (strings.Count + 1)); - var array = (char**)Marshal.AllocHGlobal((int)size); + char** array = (char**)Marshal.AllocHGlobal((int)size); Unsafe.InitBlockUnaligned(array, 0, size); for (int i = 0; i < strings.Count; i++) @@ -25,13 +26,13 @@ namespace LibKenjinx private static void ApplyFullscreenStretch(bool enable) { - var ar = enable ? AspectRatio.Stretched : AspectRatio.Fixed16x9; + AspectRatio ar = enable ? AspectRatio.Stretched : AspectRatio.Fixed16x9; - var cfg = GraphicsConfiguration; + GraphicsConfiguration cfg = GraphicsConfiguration; cfg.AspectRatio = ar; GraphicsConfiguration = cfg; - var dev = SwitchDevice?.EmulationContext; + Switch? dev = SwitchDevice?.EmulationContext; if (dev != null) { try { dev.Configuration.AspectRatio = ar; } catch { } diff --git a/src/LibKenjinx/LibKenjinx.User.cs b/src/LibKenjinx/LibKenjinx.User.cs index e86dedf9f..0d2c1a1b4 100644 --- a/src/LibKenjinx/LibKenjinx.User.cs +++ b/src/LibKenjinx/LibKenjinx.User.cs @@ -8,44 +8,44 @@ namespace LibKenjinx { public static string GetOpenedUser() { - var lastProfile = SwitchDevice?.AccountManager?.LastOpenedUser; + UserProfile? lastProfile = SwitchDevice?.AccountManager?.LastOpenedUser; return lastProfile?.UserId.ToString() ?? ""; } public static string GetUserPicture(string userId) { - var uid = new UserId(userId); + UserId uid = new(userId); - var user = SwitchDevice?.AccountManager?.GetAllUsers().FirstOrDefault(x => x.UserId == uid); + UserProfile? user = SwitchDevice?.AccountManager?.GetAllUsers().FirstOrDefault(x => x.UserId == uid); if (user == null) return ""; - var pic = user.Image; + byte[]? pic = user.Image; return pic != null ? Convert.ToBase64String(pic) : ""; } public static void SetUserPicture(string userId, string picture) { - var uid = new UserId(userId); + UserId uid = new(userId); SwitchDevice?.AccountManager?.SetUserImage(uid, Convert.FromBase64String(picture)); } public static string GetUserName(string userId) { - var uid = new UserId(userId); + UserId uid = new(userId); - var user = SwitchDevice?.AccountManager?.GetAllUsers().FirstOrDefault(x => x.UserId == uid); + UserProfile? user = SwitchDevice?.AccountManager?.GetAllUsers().FirstOrDefault(x => x.UserId == uid); return user?.Name ?? ""; } public static void SetUserName(string userId, string name) { - var uid = new UserId(userId); + UserId uid = new(userId); SwitchDevice?.AccountManager?.SetUserName(uid, name); } @@ -63,19 +63,19 @@ namespace LibKenjinx public static void DeleteUser(string userId) { - var uid = new UserId(userId); + UserId uid = new(userId); SwitchDevice?.AccountManager?.DeleteUser(uid); } public static void OpenUser(string userId) { - var uid = new UserId(userId); + UserId uid = new(userId); SwitchDevice?.AccountManager?.OpenUser(uid); } public static void CloseUser(string userId) { - var uid = new UserId(userId); + UserId uid = new(userId); SwitchDevice?.AccountManager?.CloseUser(uid); } } diff --git a/src/LibKenjinx/LibKenjinx.cs b/src/LibKenjinx/LibKenjinx.cs index 590d654ab..781772cf6 100644 --- a/src/LibKenjinx/LibKenjinx.cs +++ b/src/LibKenjinx/LibKenjinx.cs @@ -1,5 +1,6 @@ // State class for the library using Gommon; +using LibHac; using LibHac.Account; using LibHac.Common; using LibHac.Common.Keys; @@ -18,6 +19,7 @@ using Ryujinx.Common.Configuration; using Ryujinx.Common.Logging; using Ryujinx.Common.Logging.Targets; using Ryujinx.Common.Utilities; +using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.GAL.Multithreading; using Ryujinx.HLE; using Ryujinx.HLE.Kenjinx; @@ -38,7 +40,9 @@ using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; +using ApplicationId = LibHac.Ncm.ApplicationId; using Path = System.IO.Path; +using VSyncMode = Ryujinx.Common.Configuration.VSyncMode; namespace LibKenjinx { @@ -105,7 +109,7 @@ namespace LibKenjinx { return new GameStats(); } - var context = SwitchDevice.EmulationContext; + Switch? context = SwitchDevice.EmulationContext; return new GameStats { @@ -124,7 +128,7 @@ namespace LibKenjinx Logger.Info?.Print(LogClass.Application, $"Getting game info for file: {file}"); - using var stream = File.Open(file, FileMode.Open); + using FileStream stream = File.Open(file, FileMode.Open); return GetGameInfo(stream, new FileInfo(file).Extension.Remove('.')); } @@ -160,7 +164,7 @@ namespace LibKenjinx } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(gameStream.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; @@ -256,7 +260,7 @@ namespace LibKenjinx continue; } - using var icon = new UniqueRef(); + using UniqueRef icon = new(); controlFs?.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -434,7 +438,7 @@ namespace LibKenjinx foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -531,7 +535,7 @@ namespace LibKenjinx } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; @@ -554,7 +558,7 @@ namespace LibKenjinx foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -656,7 +660,7 @@ namespace LibKenjinx foreach (DirectoryEntryEx fileEntry in partitionFileSystem.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); partitionFileSystem.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -705,7 +709,7 @@ namespace LibKenjinx return false; } - var dev = SwitchDevice?.EmulationContext; + Switch? dev = SwitchDevice?.EmulationContext; if (dev == null) { Logger.Warning?.Print(LogClass.Service, "[Amiibo] Load aborted: no active EmulationContext."); @@ -714,7 +718,7 @@ namespace LibKenjinx try { - var ok = AmiiboBridge.TryLoadVirtualAmiibo(dev, data, out string msg); + bool ok = AmiiboBridge.TryLoadVirtualAmiibo(dev, data, out string msg); if (ok) Logger.Info?.Print(LogClass.Service, $"[Amiibo] Loaded {data.Length} bytes. {msg}"); else @@ -730,7 +734,7 @@ namespace LibKenjinx public static void AmiiboClear() { - var dev = SwitchDevice?.EmulationContext; + Switch? dev = SwitchDevice?.EmulationContext; if (dev == null) { Logger.Warning?.Print(LogClass.Service, "[Amiibo] Clear aborted: no active EmulationContext."); @@ -879,7 +883,7 @@ namespace LibKenjinx return false; } - var renderer = LibKenjinx.Renderer; + IRenderer renderer = LibKenjinx.Renderer; BackendThreading threadingMode = LibKenjinx.GraphicsConfiguration.BackendThreading; bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); @@ -931,7 +935,7 @@ namespace LibKenjinx public void CreateSaveDir(ulong titleId, BlitStruct nacpData) { - var applicationId = new LibHac.Ncm.ApplicationId(titleId); + ApplicationId applicationId = new(titleId); Logger.Info?.Print(LogClass.Application, $"Ensuring required savedata exists for title id: {titleId}."); @@ -964,7 +968,7 @@ namespace LibKenjinx // Call existing Horizon APIs to create/secure the saves if (LibHacHorizonManager != null) { - var rc = LibHacHorizonManager.RyujinxClient.Fs.EnsureApplicationCacheStorage(out _, out _, applicationId, in control); + Result rc = LibHacHorizonManager.RyujinxClient.Fs.EnsureApplicationCacheStorage(out _, out _, applicationId, in control); if (rc.IsFailure()) { Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {rc.ToStringWithName()}"); @@ -988,10 +992,10 @@ namespace LibKenjinx { Directory.CreateDirectory(savesRoot); - var after = Directory.GetDirectories(savesRoot); - var beforeSet = new HashSet(before, StringComparer.OrdinalIgnoreCase); + string[] after = Directory.GetDirectories(savesRoot); + HashSet beforeSet = new(before, StringComparer.OrdinalIgnoreCase); - foreach (var d in after) + foreach (string d in after) { if (!beforeSet.Contains(d)) { @@ -1053,28 +1057,28 @@ namespace LibKenjinx string mapPath = Path.Combine(savesRoot, "titleid_map.ndjson"); // titleId (lowercase) -> (Name, Folder, Timestamp) - var byTitleId = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary byTitleId = new(StringComparer.OrdinalIgnoreCase); // Read existing file try { if (File.Exists(mapPath)) { - foreach (var line in File.ReadLines(mapPath, Encoding.UTF8)) + foreach (string line in File.ReadLines(mapPath, Encoding.UTF8)) { if (string.IsNullOrWhiteSpace(line)) continue; try { - using var doc = JsonDocument.Parse(line); - var root = doc.RootElement; + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement root = doc.RootElement; - string tid = root.TryGetProperty("titleId", out var tidEl) ? (tidEl.GetString() ?? "").Trim() : ""; + string tid = root.TryGetProperty("titleId", out JsonElement tidEl) ? (tidEl.GetString() ?? "").Trim() : ""; if (string.IsNullOrEmpty(tid)) continue; - string name = root.TryGetProperty("name", out var nameEl) ? (nameEl.GetString() ?? "") : ""; - string folder = root.TryGetProperty("folder", out var folderEl) ? (folderEl.GetString() ?? "") : ""; - string ts = root.TryGetProperty("timestamp", out var tsEl) ? (tsEl.GetString() ?? "") : ""; + string name = root.TryGetProperty("name", out JsonElement nameEl) ? (nameEl.GetString() ?? "") : ""; + string folder = root.TryGetProperty("folder", out JsonElement folderEl) ? (folderEl.GetString() ?? "") : ""; + string ts = root.TryGetProperty("timestamp", out JsonElement tsEl) ? (tsEl.GetString() ?? "") : ""; byTitleId[tid.ToLowerInvariant()] = (name, folder, ts); } @@ -1090,11 +1094,11 @@ namespace LibKenjinx byTitleId.Clear(); } - var nowIso = DateTime.UtcNow.ToString("O"); - var titleIdLc = (titleIdHex ?? string.Empty).ToLowerInvariant(); + string nowIso = DateTime.UtcNow.ToString("O"); + string titleIdLc = (titleIdHex ?? string.Empty).ToLowerInvariant(); // 1) take existing folder if known - byTitleId.TryGetValue(titleIdLc, out var existing); + byTitleId.TryGetValue(titleIdLc, out (string Name, string Folder, string Timestamp) existing); string existingFolder = existing.Folder ?? ""; // 2) figure out effective folder @@ -1136,7 +1140,7 @@ namespace LibKenjinx // 5) rewrite file (stable: sort by titleId) try { - var ordered = byTitleId + IEnumerable ordered = byTitleId .OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase) .Select(kv => $"{{\"titleId\":\"{EscapeJson(kv.Key)}\",\"name\":\"{EscapeJson(kv.Value.Name)}\"," + @@ -1160,14 +1164,14 @@ namespace LibKenjinx { if (!Directory.Exists(savesRoot)) return null; - foreach (var dir in Directory.GetDirectories(savesRoot)) + foreach (string dir in Directory.GetDirectories(savesRoot)) { string marker = Path.Combine(dir, "TITLEID.txt"); if (!File.Exists(marker)) continue; try { - using var sr = new StreamReader(marker, Encoding.UTF8, true); + using StreamReader sr = new(marker, Encoding.UTF8, true); string? first = sr.ReadLine()?.Trim().ToLowerInvariant(); if (first == titleIdLc) { @@ -1199,7 +1203,7 @@ namespace LibKenjinx int idx = (int)Language.AmericanEnglish; if (control.Title.Length > idx) { - var s = control.Title[idx].NameString.ToString(); + string? s = control.Title[idx].NameString.ToString(); if (!string.IsNullOrWhiteSpace(s)) return s; } diff --git a/src/LibKenjinx/VulkanLoader.cs b/src/LibKenjinx/VulkanLoader.cs index 803b6c752..78fb11081 100644 --- a/src/LibKenjinx/VulkanLoader.cs +++ b/src/LibKenjinx/VulkanLoader.cs @@ -30,8 +30,8 @@ namespace LibKenjinx if (_loadedLibrary != nint.Zero) { - var instanceGetProc = NativeLibrary.GetExport(_loadedLibrary, "vkGetInstanceProcAddr"); - var deviceProc = NativeLibrary.GetExport(_loadedLibrary, "vkGetDeviceProcAddr"); + IntPtr instanceGetProc = NativeLibrary.GetExport(_loadedLibrary, "vkGetInstanceProcAddr"); + IntPtr deviceProc = NativeLibrary.GetExport(_loadedLibrary, "vkGetDeviceProcAddr"); _getInstanceProcAddr = Marshal.GetDelegateForFunctionPointer(instanceGetProc); _getDeviceProcAddr = Marshal.GetDelegateForFunctionPointer(deviceProc); @@ -45,13 +45,13 @@ namespace LibKenjinx { return Vk.GetApi(); } - var ctx = new MultiNativeContext(new INativeContext[1]); - var ret = new Vk(ctx); + MultiNativeContext? ctx = new(new INativeContext[1]); + Vk ret = new Vk(ctx); ctx.Contexts[0] = new LamdaNativeContext ( x => { - var xPtr = Marshal.StringToHGlobalAnsi(x); + IntPtr xPtr = Marshal.StringToHGlobalAnsi(x); byte* xp = (byte*)xPtr; try { @@ -64,7 +64,7 @@ namespace LibKenjinx if (ptr == 0) { - var currentDevice = ret.CurrentDevice.GetValueOrDefault().Handle; + IntPtr currentDevice = ret.CurrentDevice.GetValueOrDefault().Handle; if (currentDevice != nint.Zero) { ptr = _getDeviceProcAddr(currentDevice, xPtr); diff --git a/src/Ryujinx.Audio.Backends.SDL3/SDL3HardwareDeviceDriver.cs b/src/Ryujinx.Audio.Backends.SDL3/SDL3HardwareDeviceDriver.cs index 598de8835..045063a5a 100644 --- a/src/Ryujinx.Audio.Backends.SDL3/SDL3HardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio.Backends.SDL3/SDL3HardwareDeviceDriver.cs @@ -130,7 +130,7 @@ namespace Ryujinx.Audio.Backends.SDL3 { SDL_AudioSpec desired = GetSDL3Spec(requestedSampleFormat, requestedSampleRate, requestedChannelCount); SDL_AudioSpec got = desired; - var pCallback = callback != null ? (SDL_AudioStreamCallbackPointer)Marshal.GetFunctionPointerForDelegate(callback) : null; + SDL_AudioStreamCallbackPointer pCallback = callback != null ? (SDL_AudioStreamCallbackPointer)Marshal.GetFunctionPointerForDelegate(callback) : null; // From SDL 3 and on, SDL requires us to set this as a hint SDL_SetHint(SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES, $"{sampleCount}"); diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs index 3f7a745cd..a69bd3616 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs @@ -38,7 +38,7 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native get => Marshal.PtrToStringAnsi(GetOutContext().Name); set { - var context = GetOutContext(); + SoundIoOutStream context = GetOutContext(); if (_nameStored != nint.Zero && context.Name == _nameStored) { @@ -129,8 +129,8 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native unsafe { - var frameCountPtr = &nativeFrameCount; - var arenasPtr = &arenas; + int* frameCountPtr = &nativeFrameCount; + IntPtr* arenasPtr = &arenas; CheckError(soundio_outstream_begin_write(_context, (nint)arenasPtr, (nint)frameCountPtr)); frameCount = *frameCountPtr; diff --git a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs index bc2313ccf..008a067f1 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Audio.Renderer.Utils private void UpdateHeader() { - var writer = new BinaryWriter(_stream); + BinaryWriter writer = new(_stream); long currentPos = writer.Seek(0, SeekOrigin.Current); diff --git a/src/Ryujinx.Common/AsyncWorkQueue.cs b/src/Ryujinx.Common/AsyncWorkQueue.cs index abb5867b0..e3f91c891 100644 --- a/src/Ryujinx.Common/AsyncWorkQueue.cs +++ b/src/Ryujinx.Common/AsyncWorkQueue.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Common { try { - foreach (var item in _queue.GetConsumingEnumerable(_cts.Token)) + foreach (T item in _queue.GetConsumingEnumerable(_cts.Token)) { _workerAction(item); } diff --git a/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs b/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs index 98fe38060..c4b33ab0d 100644 --- a/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs +++ b/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Buffers; using System.Diagnostics; +using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,15 +17,15 @@ namespace Ryujinx.Common.Extensions /// The path and name of the file to create and dump to public static void DumpToFile(this ref SequenceReader reader, string fileFullName) { - var initialConsumed = reader.Consumed; + long initialConsumed = reader.Consumed; reader.Rewind(initialConsumed); - using (var fileStream = System.IO.File.Create(fileFullName, 4096, System.IO.FileOptions.None)) + using (FileStream fileStream = System.IO.File.Create(fileFullName, 4096, System.IO.FileOptions.None)) { while (reader.End == false) { - var span = reader.CurrentSpan; + ReadOnlySpan span = reader.CurrentSpan; fileStream.Write(span); reader.Advance(span.Length); } diff --git a/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs b/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs index b1cc0eae3..a7b4da40f 100644 --- a/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs +++ b/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Common.Logging.Formatters sb.Append('{'); - foreach (var prop in props) + foreach (PropertyInfo prop in props) { sb.Append(prop.Name); sb.Append(": "); @@ -52,7 +52,7 @@ namespace Ryujinx.Common.Logging.Formatters if (array is not null) { - foreach (var item in array) + foreach (object? item in array) { sb.Append(item); sb.Append(", "); diff --git a/src/Ryujinx.Common/Logging/Logger.cs b/src/Ryujinx.Common/Logging/Logger.cs index 662df8834..dae2554d8 100644 --- a/src/Ryujinx.Common/Logging/Logger.cs +++ b/src/Ryujinx.Common/Logging/Logger.cs @@ -207,7 +207,7 @@ namespace Ryujinx.Common.Logging _stdErrAdapter.Dispose(); - foreach (var target in _logTargets) + foreach (ILogTarget target in _logTargets) { target.Dispose(); } @@ -217,9 +217,9 @@ namespace Ryujinx.Common.Logging public static IReadOnlyCollection GetEnabledLevels() { - var logs = new[] { Debug, Info, Warning, Error, Guest, AccessLog, Stub, Trace }; + Log?[] logs = new[] { Debug, Info, Warning, Error, Guest, AccessLog, Stub, Trace }; List levels = new(logs.Length); - foreach (var log in logs) + foreach (Log? log in logs) { if (log.HasValue) { diff --git a/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs b/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs index 34f52d6ab..a5d5a5875 100644 --- a/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs +++ b/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs @@ -94,7 +94,7 @@ namespace Ryujinx.Common.Logging.Targets return; } - using var signal = new ManualResetEventSlim(false); + using ManualResetEventSlim signal = new(false); try { _messageQueue.Add(new FlushEventArgs(signal)); diff --git a/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs b/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs index c5bf23cdb..88b324a36 100644 --- a/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs +++ b/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Common.Logging.Targets public void Log(object sender, LogEventArgs e) { - var logEventArgsJson = LogEventArgsJson.FromLogEventArgs(e); + LogEventArgsJson logEventArgsJson = LogEventArgsJson.FromLogEventArgs(e); JsonHelper.SerializeToStream(_stream, logEventArgsJson, LogEventJsonSerializerContext.Default.LogEventArgsJson); } diff --git a/src/Ryujinx.Common/Utilities/EmbeddedResources.cs b/src/Ryujinx.Common/Utilities/EmbeddedResources.cs index 7530c012a..45bb7d537 100644 --- a/src/Ryujinx.Common/Utilities/EmbeddedResources.cs +++ b/src/Ryujinx.Common/Utilities/EmbeddedResources.cs @@ -19,21 +19,21 @@ namespace Ryujinx.Common public static byte[] Read(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return Read(assembly, path); } public static Task ReadAsync(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAsync(assembly, path); } public static byte[] Read(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; @@ -44,14 +44,14 @@ namespace Ryujinx.Common public static MemoryOwner ReadFileToRentedMemory(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadFileToRentedMemory(assembly, path); } public static MemoryOwner ReadFileToRentedMemory(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); return stream is null ? null @@ -60,7 +60,7 @@ namespace Ryujinx.Common public async static Task ReadAsync(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; @@ -71,55 +71,55 @@ namespace Ryujinx.Common public static string ReadAllText(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAllText(assembly, path); } public static Task ReadAllTextAsync(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAllTextAsync(assembly, path); } public static string ReadAllText(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; } - using var reader = new StreamReader(stream); + using StreamReader reader = new(stream); return reader.ReadToEnd(); } public async static Task ReadAllTextAsync(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; } - using var reader = new StreamReader(stream); + using StreamReader reader = new(stream); return await reader.ReadToEndAsync(); } public static Stream GetStream(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return GetStream(assembly, path); } public static Stream GetStream(Assembly assembly, string filename) { - var @namespace = assembly.GetName().Name; - var manifestUri = @namespace + "." + filename.Replace('/', '.'); + string @namespace = assembly.GetName().Name; + string manifestUri = @namespace + "." + filename.Replace('/', '.'); - var stream = assembly.GetManifestResourceStream(manifestUri); + Stream stream = assembly.GetManifestResourceStream(manifestUri); return stream; } @@ -133,11 +133,11 @@ namespace Ryujinx.Common private static (Assembly, string) ResolveManifestPath(string filename) { - var segments = filename.Split('/', 2, StringSplitOptions.RemoveEmptyEntries); + string[] segments = filename.Split('/', 2, StringSplitOptions.RemoveEmptyEntries); if (segments.Length >= 2) { - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GetName().Name == segments[0]) { diff --git a/src/Ryujinx.Common/Utilities/FileSystemUtils.cs b/src/Ryujinx.Common/Utilities/FileSystemUtils.cs index a57fa8a78..97510fd9d 100644 --- a/src/Ryujinx.Common/Utilities/FileSystemUtils.cs +++ b/src/Ryujinx.Common/Utilities/FileSystemUtils.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Common.Utilities public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive) { // Get information about the source directory - var dir = new DirectoryInfo(sourceDir); + DirectoryInfo dir = new(sourceDir); // Check if the source directory exists if (!dir.Exists) @@ -49,7 +49,7 @@ namespace Ryujinx.Common.Utilities public static string SanitizeFileName(string fileName) { - var reservedChars = new HashSet(Path.GetInvalidFileNameChars()); + HashSet reservedChars = new(Path.GetInvalidFileNameChars()); return string.Concat(fileName.Select(c => reservedChars.Contains(c) ? '_' : c)); } } diff --git a/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs b/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs index 426cd46b7..fa04ee347 100644 --- a/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs +++ b/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs @@ -1,5 +1,6 @@ using MsgPack; using System; +using System.Collections.Generic; using System.Text; namespace Ryujinx.Common.Utilities @@ -18,7 +19,7 @@ namespace Ryujinx.Common.Utilities public static string Format(MessagePackObject obj) { - var builder = new IndentedStringBuilder(); + IndentedStringBuilder builder = new(); FormatMsgPackObj(obj, builder); @@ -41,7 +42,7 @@ namespace Ryujinx.Common.Utilities } else { - var literal = obj.ToObject(); + object literal = obj.ToObject(); if (literal is String) { @@ -88,7 +89,7 @@ namespace Ryujinx.Common.Utilities { builder.Append("[ "); - foreach (var b in arr) + foreach (byte b in arr) { builder.Append("0x"); builder.Append(ToHexChar(b >> 4)); @@ -111,7 +112,7 @@ namespace Ryujinx.Common.Utilities builder.Append("0x"); } - foreach (var b in arr) + foreach (byte b in arr) { builder.Append(ToHexChar(b >> 4)); builder.Append(ToHexChar(b & 0xF)); @@ -122,7 +123,7 @@ namespace Ryujinx.Common.Utilities private static void FormatMsgPackMap(MessagePackObject obj, IndentedStringBuilder builder) { - var map = obj.AsDictionary(); + MessagePackObjectDictionary map = obj.AsDictionary(); builder.Append('{'); @@ -130,7 +131,7 @@ namespace Ryujinx.Common.Utilities builder.IncreaseIndent() .AppendLine(); - foreach (var item in map) + foreach (KeyValuePair item in map) { FormatMsgPackObj(item.Key, builder); @@ -154,11 +155,11 @@ namespace Ryujinx.Common.Utilities private static void FormatMsgPackArray(MessagePackObject obj, IndentedStringBuilder builder) { - var arr = obj.AsList(); + IList arr = obj.AsList(); builder.Append("[ "); - foreach (var item in arr) + foreach (MessagePackObject item in arr) { FormatMsgPackObj(item, builder); diff --git a/src/Ryujinx.Common/Utilities/StreamUtils.cs b/src/Ryujinx.Common/Utilities/StreamUtils.cs index aeb6e0d52..60391a902 100644 --- a/src/Ryujinx.Common/Utilities/StreamUtils.cs +++ b/src/Ryujinx.Common/Utilities/StreamUtils.cs @@ -1,5 +1,6 @@ using Microsoft.IO; using Ryujinx.Common.Memory; +using System; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -27,7 +28,7 @@ namespace Ryujinx.Common.Utilities MemoryOwner ownedMemory = MemoryOwner.Rent(checked((int)bytesExpected)); - var destSpan = ownedMemory.Span; + Span destSpan = ownedMemory.Span; int totalBytesRead = 0; diff --git a/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs b/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs index 15b8daf1c..010b60637 100644 --- a/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs +++ b/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Common.Utilities { internal static TimeSpan Measure(Action action) { - var sw = new Stopwatch(); + Stopwatch sw = new(); sw.Start(); try @@ -66,7 +66,7 @@ namespace Ryujinx.Common.Utilities { if (Path.GetExtension(filename).Equals(".XCI", StringComparison.InvariantCultureIgnoreCase)) { - var trimmer = new XCIFileTrimmer(filename, log); + XCIFileTrimmer trimmer = new(filename, log); return trimmer.CanBeTrimmed; } @@ -77,7 +77,7 @@ namespace Ryujinx.Common.Utilities { if (Path.GetExtension(filename).Equals(".XCI", StringComparison.InvariantCultureIgnoreCase)) { - var trimmer = new XCIFileTrimmer(filename, log); + XCIFileTrimmer trimmer = new(filename, log); return trimmer.CanBeUntrimmed; } @@ -221,7 +221,7 @@ namespace Ryujinx.Common.Utilities { long maxReads = readSizeB / BufferSize; long read = 0; - var buffer = new byte[BufferSize]; + byte[] buffer = new byte[BufferSize]; while (true) { @@ -287,7 +287,7 @@ namespace Ryujinx.Common.Utilities try { - var info = new FileInfo(Filename); + FileInfo info = new(Filename); if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { try @@ -308,7 +308,7 @@ namespace Ryujinx.Common.Utilities return OperationOutcome.FileSizeChanged; } - var outfileStream = new FileStream(_filename, FileMode.Open, FileAccess.Write, FileShare.Write); + FileStream outfileStream = new(_filename, FileMode.Open, FileAccess.Write, FileShare.Write); try { @@ -347,7 +347,7 @@ namespace Ryujinx.Common.Utilities { Log?.Write(LogType.Info, "Untrimming..."); - var info = new FileInfo(Filename); + FileInfo info = new(Filename); if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { try @@ -368,7 +368,7 @@ namespace Ryujinx.Common.Utilities return OperationOutcome.FileSizeChanged; } - var outfileStream = new FileStream(_filename, FileMode.Append, FileAccess.Write, FileShare.Write); + FileStream outfileStream = new(_filename, FileMode.Append, FileAccess.Write, FileShare.Write); long bytesToWriteB = UntrimmedFileSizeB - FileSizeB; try @@ -413,7 +413,7 @@ namespace Ryujinx.Common.Utilities try { - var buffer = new byte[BufferSize]; + byte[] buffer = new byte[BufferSize]; Array.Fill(buffer, PaddingByte); while (bytesLeftToWriteB > 0) diff --git a/src/Ryujinx.Cpu/AddressTable.cs b/src/Ryujinx.Cpu/AddressTable.cs index 537b132b8..774908a46 100644 --- a/src/Ryujinx.Cpu/AddressTable.cs +++ b/src/Ryujinx.Cpu/AddressTable.cs @@ -49,7 +49,7 @@ namespace ARMeilleure.Common public TableSparseBlock(ulong size, Action ensureMapped, PageInitDelegate pageInit) { - var block = new SparseMemoryBlock(size, pageInit, null); + SparseMemoryBlock block = new(size, pageInit, null); _trackingEvent = (ulong address, ulong _, bool _) => { @@ -146,7 +146,7 @@ namespace ARMeilleure.Common Levels = levels; Mask = 0; - foreach (var level in Levels) + foreach (AddressTableLevel level in Levels) { Mask |= level.Mask; } @@ -366,7 +366,7 @@ namespace ARMeilleure.Common /// The new sparse block that was added private TableSparseBlock ReserveNewSparseBlock() { - var block = new TableSparseBlock(_sparseBlockSize, EnsureMapped, InitLeafPage); + TableSparseBlock block = new(_sparseBlockSize, EnsureMapped, InitLeafPage); _sparseReserved.Add(block); _sparseReservedOffset = 0; @@ -384,7 +384,7 @@ namespace ARMeilleure.Common /// Allocated block private nint Allocate(int length, T fill, bool leaf) where T : unmanaged { - var size = sizeof(T) * length; + int size = sizeof(T) * length; AddressTablePage page; @@ -416,10 +416,10 @@ namespace ARMeilleure.Common } else { - var address = (nint)NativeAllocator.Instance.Allocate((uint)size); + IntPtr address = (nint)NativeAllocator.Instance.Allocate((uint)size); page = new AddressTablePage(false, address); - var span = new Span((void*)page.Address, length); + Span span = new((void*)page.Address, length); span.Fill(fill); } @@ -448,7 +448,7 @@ namespace ARMeilleure.Common { if (!_disposed) { - foreach (var page in _pages) + foreach (AddressTablePage page in _pages) { if (!page.IsSparse) { diff --git a/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs b/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs index eb7c0ef08..662e50793 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Cpu.AppleHv public HvAddressSpace(MemoryBlock backingMemory, ulong asSize) { - (_asBase, var ipaAllocator) = HvVm.CreateAddressSpace(backingMemory); + (_asBase, HvIpaAllocator ipaAllocator) = HvVm.CreateAddressSpace(backingMemory); _backingSize = backingMemory.Size; _userRange = new HvAddressSpaceRange(ipaAllocator); diff --git a/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs b/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs index 86936c592..779579e6a 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Cpu.AppleHv public HvMemoryBlockAllocation Allocate(ulong size, ulong alignment) { - var allocation = Allocate(size, alignment, CreateBlock); + Allocation allocation = Allocate(size, alignment, CreateBlock); return new HvMemoryBlockAllocation(this, allocation.Block, allocation.Offset, allocation.Size); } diff --git a/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs b/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs index 5cb4b17e7..f1a8458b4 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs @@ -237,17 +237,17 @@ namespace Ryujinx.Cpu.AppleHv return []; } - var guestRegions = GetPhysicalRegionsImpl(va, size); + List guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { return null; } - var regions = new HostMemoryRange[guestRegions.Count]; + HostMemoryRange[] regions = new HostMemoryRange[guestRegions.Count]; for (int i = 0; i < regions.Length; i++) { - var guestRegion = guestRegions[i]; + MemoryRange guestRegion = guestRegions[i]; nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); regions[i] = new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); } @@ -275,7 +275,7 @@ namespace Ryujinx.Cpu.AppleHv int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressInternal(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs b/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs index ee91c478b..c4eec31a6 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Cpu.AppleHv { // Calculate our time delta in ticks based on the current clock frequency. - int result = TimeApi.mach_timebase_info(out var timeBaseInfo); + int result = TimeApi.mach_timebase_info(out MachTimebaseInfo timeBaseInfo); Debug.Assert(result == 0); diff --git a/src/Ryujinx.Cpu/AppleHv/HvVm.cs b/src/Ryujinx.Cpu/AppleHv/HvVm.cs index a61dcd96a..6ad44621b 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvVm.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvVm.cs @@ -38,7 +38,7 @@ namespace Ryujinx.Cpu.AppleHv baseAddress = ipaAllocator.Allocate(block.Size, AsIpaAlignment); } - var rwx = HvMemoryFlags.Read | HvMemoryFlags.Write | HvMemoryFlags.Exec; + HvMemoryFlags rwx = HvMemoryFlags.Read | HvMemoryFlags.Write | HvMemoryFlags.Exec; HvApi.hv_vm_map((ulong)block.Pointer, baseAddress, block.Size, rwx).ThrowOnError(); diff --git a/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs b/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs index 08effc47c..4d5303d70 100644 --- a/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs +++ b/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs @@ -127,7 +127,7 @@ namespace Ryujinx.Cpu.Jit.HostTracked Debug.Assert(leftSize > 0); Debug.Assert(rightSize > 0); - (var leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize); + (PrivateMemoryAllocation leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize); PrivateMapping left = new(Address, leftSize, leftAllocation); diff --git a/src/Ryujinx.Cpu/Jit/MemoryManager.cs b/src/Ryujinx.Cpu/Jit/MemoryManager.cs index ae1075f60..5ab51d1fb 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManager.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManager.cs @@ -257,17 +257,17 @@ namespace Ryujinx.Cpu.Jit return []; } - var guestRegions = GetPhysicalRegionsImpl(va, size); + List guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { return null; } - var regions = new HostMemoryRange[guestRegions.Count]; + HostMemoryRange[] regions = new HostMemoryRange[guestRegions.Count]; for (int i = 0; i < regions.Length; i++) { - var guestRegion = guestRegions[i]; + MemoryRange guestRegion = guestRegions[i]; nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); regions[i] = new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); } @@ -295,7 +295,7 @@ namespace Ryujinx.Cpu.Jit int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressInternal(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs b/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs index 2689a8982..4cd75b623 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs @@ -345,7 +345,7 @@ namespace Ryujinx.Cpu.Jit { int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressChecked(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/Jit/MemoryManagerHostNoMirror.cs b/src/Ryujinx.Cpu/Jit/MemoryManagerHostNoMirror.cs index cccc17fda..92e9b073a 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManagerHostNoMirror.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManagerHostNoMirror.cs @@ -175,17 +175,17 @@ namespace Ryujinx.Cpu.Jit return Enumerable.Empty(); } - var guestRegions = GetPhysicalRegionsImpl(va, size); + List guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { return null; } - var regions = new HostMemoryRange[guestRegions.Count]; + HostMemoryRange[] regions = new HostMemoryRange[guestRegions.Count]; for (int i = 0; i < regions.Length; i++) { - var guestRegion = guestRegions[i]; + MemoryRange guestRegion = guestRegions[i]; nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); regions[i] = new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); } @@ -213,7 +213,7 @@ namespace Ryujinx.Cpu.Jit int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressInternal(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs b/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs index 526af03ee..f72873f25 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs @@ -249,7 +249,7 @@ namespace Ryujinx.Cpu.Jit if (TryGetVirtualContiguous(va, data.Length, out MemoryBlock memoryBlock, out ulong offset)) { - var target = memoryBlock.GetSpan(offset, data.Length); + Span target = memoryBlock.GetSpan(offset, data.Length); bool changed = !data.SequenceEqual(target); @@ -448,7 +448,7 @@ namespace Ryujinx.Cpu.Jit return null; } - var regions = new List(); + List regions = new(); ulong endVa = va + size; try @@ -489,7 +489,7 @@ namespace Ryujinx.Cpu.Jit int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressInternal(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs b/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs index 48bdbb573..6a8c2abdd 100644 --- a/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs +++ b/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs @@ -205,7 +205,7 @@ namespace Ryujinx.Cpu.LightningJit.Arm32.Target.Arm64 for (int i = 0; i < funcTable.Levels.Length; i++) { - var level = funcTable.Levels[i]; + AddressTableLevel level = funcTable.Levels[i]; asm.Ubfx(indexReg, guestAddress, level.Index, level.Length); asm.Lsl(indexReg, indexReg, Const(3)); diff --git a/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs b/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs index 09f19ae04..1e24673a5 100644 --- a/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs +++ b/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs @@ -370,7 +370,7 @@ namespace Ryujinx.Cpu.LightningJit.Arm64.Target.Arm64 for (int i = 0; i < funcTable.Levels.Length; i++) { - var level = funcTable.Levels[i]; + AddressTableLevel level = funcTable.Levels[i]; asm.Ubfx(indexReg, guestAddress, level.Index, level.Length); asm.Lsl(indexReg, indexReg, Const(3)); diff --git a/src/Ryujinx.Cpu/LightningJit/Cache/JitCache.cs b/src/Ryujinx.Cpu/LightningJit/Cache/JitCache.cs index bcc9eefc6..70fd3d07f 100644 --- a/src/Ryujinx.Cpu/LightningJit/Cache/JitCache.cs +++ b/src/Ryujinx.Cpu/LightningJit/Cache/JitCache.cs @@ -262,7 +262,7 @@ namespace Ryujinx.Cpu.LightningJit.Cache { entry = _cacheEntries[index]; - if (Optimizations.CacheEviction && _entryUsageStats.TryGetValue(offset, out var stats)) + if (Optimizations.CacheEviction && _entryUsageStats.TryGetValue(offset, out EntryUsageStats stats)) { stats.UpdateUsage(); } diff --git a/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs b/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs index 53b2f8bd3..65d297c28 100644 --- a/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs +++ b/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Cpu.LightningJit.Cache private bool TryGetThreadLocalFunction(ulong guestAddress, out nint funcPtr) { - if ((_threadLocalCache ??= new()).TryGetValue(guestAddress, out var entry)) + if ((_threadLocalCache ??= new()).TryGetValue(guestAddress, out ThreadLocalCacheEntry entry)) { if (entry.IncrementUseCount() >= MinCallsForPad) { diff --git a/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs b/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs index abb6e7c34..dd130dbeb 100644 --- a/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs +++ b/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int targetIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.TargetIndex = targetIndex; state.HasTarget = true; @@ -68,7 +68,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -94,7 +94,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -113,7 +113,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -342,7 +342,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 public readonly void Cset(Operand rd, ArmCondition condition) { - var zr = new Operand(ZrRegister, RegisterType.Integer, rd.Type); + Operand zr = new(ZrRegister, RegisterType.Integer, rd.Type); Csinc(rd, zr, zr, (ArmCondition)((int)condition ^ 1)); } diff --git a/src/Ryujinx.Cpu/LightningJit/Translator.cs b/src/Ryujinx.Cpu/LightningJit/Translator.cs index 5c5595b1b..5f3fe8783 100644 --- a/src/Ryujinx.Cpu/LightningJit/Translator.cs +++ b/src/Ryujinx.Cpu/LightningJit/Translator.cs @@ -162,14 +162,14 @@ namespace Ryujinx.Cpu.LightningJit { List functions = Functions.AsList(); - foreach (var func in functions) + foreach (TranslatedFunction func in functions) { JitCache.Unmap(func.FuncPointer); } Functions.Clear(); - while (_oldFuncs.TryDequeue(out var kv)) + while (_oldFuncs.TryDequeue(out KeyValuePair kv)) { JitCache.Unmap(kv.Value.FuncPointer); } diff --git a/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs b/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs index 43d7dc929..d0eec7eff 100644 --- a/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs +++ b/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs @@ -174,7 +174,7 @@ namespace Ryujinx.Cpu.LightningJit for (int i = 0; i < _functionTable.Levels.Length; i++) { - ref var level = ref _functionTable.Levels[i]; + ref AddressTableLevel level = ref _functionTable.Levels[i]; asm.Mov(mask, level.Mask >> level.Index); asm.And(index, mask, guestAddress, ArmShiftType.Lsr, level.Index); diff --git a/src/Ryujinx.Cpu/Nce/Arm64/Assembler.cs b/src/Ryujinx.Cpu/Nce/Arm64/Assembler.cs index 5f3c6369e..574d4c783 100644 --- a/src/Ryujinx.Cpu/Nce/Arm64/Assembler.cs +++ b/src/Ryujinx.Cpu/Nce/Arm64/Assembler.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Cpu.Nce.Arm64 { int targetIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.TargetIndex = targetIndex; state.HasTarget = true; @@ -68,7 +68,7 @@ namespace Ryujinx.Cpu.Nce.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -94,7 +94,7 @@ namespace Ryujinx.Cpu.Nce.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -113,7 +113,7 @@ namespace Ryujinx.Cpu.Nce.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -225,7 +225,7 @@ namespace Ryujinx.Cpu.Nce.Arm64 public void Cset(Operand rd, ArmCondition condition) { - var zr = new Operand(ZrRegister, RegisterType.Integer, rd.Type); + Operand zr = new(ZrRegister, RegisterType.Integer, rd.Type); Csinc(rd, zr, zr, (ArmCondition)((int)condition ^ 1)); } diff --git a/src/Ryujinx.Cpu/Nce/MemoryManagerNative.cs b/src/Ryujinx.Cpu/Nce/MemoryManagerNative.cs index 3ea0a1a61..8b75b1ec2 100644 --- a/src/Ryujinx.Cpu/Nce/MemoryManagerNative.cs +++ b/src/Ryujinx.Cpu/Nce/MemoryManagerNative.cs @@ -163,17 +163,17 @@ namespace Ryujinx.Cpu.Nce return Enumerable.Empty(); } - var guestRegions = GetPhysicalRegionsImpl(va, size); + List guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { return null; } - var regions = new HostMemoryRange[guestRegions.Count]; + HostMemoryRange[] regions = new HostMemoryRange[guestRegions.Count]; for (int i = 0; i < regions.Length; i++) { - var guestRegion = guestRegions[i]; + MemoryRange guestRegion = guestRegions[i]; nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); regions[i] = new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); } @@ -201,7 +201,7 @@ namespace Ryujinx.Cpu.Nce int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new(); ulong regionStart = GetPhysicalAddressInternal(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/Nce/NceCpuCodePatch.cs b/src/Ryujinx.Cpu/Nce/NceCpuCodePatch.cs index bb1f65109..d545e4703 100644 --- a/src/Ryujinx.Cpu/Nce/NceCpuCodePatch.cs +++ b/src/Ryujinx.Cpu/Nce/NceCpuCodePatch.cs @@ -50,7 +50,7 @@ namespace Ryujinx.Cpu.Nce { uint[] code = _code.ToArray(); - foreach (var patchTarget in _patchTargets) + foreach (PatchTarget patchTarget in _patchTargets) { ulong instPatchStartAddress = patchAddress + (ulong)patchTarget.PatchStartIndex * sizeof(uint); ulong instPatchBranchAddress = patchAddress + (ulong)patchTarget.PatchBranchIndex * sizeof(uint); diff --git a/src/Ryujinx.Cpu/Nce/NceExecutionContext.cs b/src/Ryujinx.Cpu/Nce/NceExecutionContext.cs index 492ee3371..b5b956c3a 100644 --- a/src/Ryujinx.Cpu/Nce/NceExecutionContext.cs +++ b/src/Ryujinx.Cpu/Nce/NceExecutionContext.cs @@ -74,7 +74,7 @@ namespace Ryujinx.Cpu.Nce _context = new NceNativeContext(); - ref var storage = ref _context.GetStorage(); + ref NceNativeContext.NativeCtxStorage storage = ref _context.GetStorage(); storage.SvcCallHandler = svcHandlerPtr; storage.InManaged = 1u; storage.CtrEl0 = 0x8444c004; // TODO: Get value from host CPU instead of using guest one? @@ -99,7 +99,7 @@ namespace Ryujinx.Cpu.Nce public void SetStartAddress(ulong address) { - ref var storage = ref _context.GetStorage(); + ref NceNativeContext.NativeCtxStorage storage = ref _context.GetStorage(); storage.X[30] = address; storage.HostThreadHandle = NceThreadPal.GetCurrentThreadHandle(); diff --git a/src/Ryujinx.Cpu/Nce/NcePatcher.cs b/src/Ryujinx.Cpu/Nce/NcePatcher.cs index e3ca0d00a..f6be5d96f 100644 --- a/src/Ryujinx.Cpu/Nce/NcePatcher.cs +++ b/src/Ryujinx.Cpu/Nce/NcePatcher.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Cpu.Nce { NceCpuCodePatch codePatch = new(); - var textUint = MemoryMarshal.Cast(textSection); + ReadOnlySpan textUint = MemoryMarshal.Cast(textSection); for (int i = 0; i < textUint.Length; i++) { diff --git a/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs b/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs index d4c33b7c3..6a6e6671f 100644 --- a/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs +++ b/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Cpu { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -84,7 +84,7 @@ namespace Ryujinx.Cpu private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -97,7 +97,7 @@ namespace Ryujinx.Cpu private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -149,7 +149,7 @@ namespace Ryujinx.Cpu public PrivateMemoryAllocation Allocate(ulong size, ulong alignment) { - var allocation = Allocate(size, alignment, CreateBlock); + Allocation allocation = Allocate(size, alignment, CreateBlock); return new PrivateMemoryAllocation(this, allocation.Block, allocation.Offset, allocation.Size); } @@ -200,7 +200,7 @@ namespace Ryujinx.Cpu for (int i = 0; i < _blocks.Count; i++) { - var block = _blocks[i]; + T block = _blocks[i]; if (block.Size >= size) { @@ -214,8 +214,8 @@ namespace Ryujinx.Cpu ulong blockAlignedSize = BitUtils.AlignUp(size, _blockAlignment); - var memory = new MemoryBlock(blockAlignedSize, _allocationFlags); - var newBlock = createBlock(memory, blockAlignedSize); + MemoryBlock memory = new(blockAlignedSize, _allocationFlags); + T newBlock = createBlock(memory, blockAlignedSize); InsertBlock(newBlock); diff --git a/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs b/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs index 1da59a95a..0c1206cf2 100644 --- a/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs +++ b/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs @@ -104,7 +104,7 @@ namespace Ryujinx.Cpu.Signal _signalHandlerPtr = customSignalHandlerFactory(UnixSignalHandlerRegistration.GetSegfaultExceptionHandler().sa_handler, _signalHandlerPtr); } - var old = UnixSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr); + UnixSignalHandlerRegistration.SigAction old = UnixSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr); config.UnixOldSigaction = (nuint)(ulong)old.sa_handler; config.UnixOldSigaction3Arg = old.sa_flags & 4; diff --git a/src/Ryujinx.Graphics.Device/DeviceState.cs b/src/Ryujinx.Graphics.Device/DeviceState.cs index 15266b663..95464ef13 100644 --- a/src/Ryujinx.Graphics.Device/DeviceState.cs +++ b/src/Ryujinx.Graphics.Device/DeviceState.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -32,15 +33,15 @@ namespace Ryujinx.Graphics.Device _debugLogCallback = debugLogCallback; } - var fields = typeof(TState).GetFields(); + FieldInfo[] fields = typeof(TState).GetFields(); int offset = 0; for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++) { - var field = fields[fieldIndex]; + FieldInfo field = fields[fieldIndex]; - var currentFieldOffset = (int)Marshal.OffsetOf(field.Name); - var nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); + int currentFieldOffset = (int)Marshal.OffsetOf(field.Name); + int nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); int sizeOfField = nextFieldOffset - currentFieldOffset; @@ -48,7 +49,7 @@ namespace Ryujinx.Graphics.Device { int index = (offset + i) / RegisterSize; - if (callbacks != null && callbacks.TryGetValue(field.Name, out var cb)) + if (callbacks != null && callbacks.TryGetValue(field.Name, out RwCallback cb)) { if (cb.Read != null) { diff --git a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs index 4f3606ac7..88ec90019 100644 --- a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs +++ b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs @@ -361,7 +361,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public unsafe bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual) { - var evt = value as ThreadedCounterEvent; + ThreadedCounterEvent evt = value as ThreadedCounterEvent; if (evt != null) { if (compare == 0 && evt.Type == CounterType.SamplesPassed && evt.ClearCounter) diff --git a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs index 4c8d7d372..12480e3ed 100644 --- a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs +++ b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs @@ -294,7 +294,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public unsafe IImageArray CreateImageArray(int size, bool isBuffer) { - var imageArray = new ThreadedImageArray(this); + ThreadedImageArray imageArray = new(this); New()->Set(Ref(imageArray), size, isBuffer); QueueCommand(); @@ -303,7 +303,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public unsafe IProgram CreateProgram(ShaderSource[] shaders, ShaderInfo info) { - var program = new ThreadedProgram(this); + ThreadedProgram program = new(this); SourceProgramRequest request = new(program, shaders, info); @@ -319,7 +319,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public unsafe ISampler CreateSampler(SamplerCreateInfo info) { - var sampler = new ThreadedSampler(this); + ThreadedSampler sampler = new(this); New()->Set(Ref(sampler), info); QueueCommand(); @@ -337,7 +337,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading { if (IsGpuThread()) { - var texture = new ThreadedTexture(this, info); + ThreadedTexture texture = new(this, info); New()->Set(Ref(texture), info); QueueCommand(); @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading } else { - var texture = new ThreadedTexture(this, info) + ThreadedTexture texture = new(this, info) { Base = _baseRenderer.CreateTexture(info), }; @@ -355,7 +355,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading } public unsafe ITextureArray CreateTextureArray(int size, bool isBuffer) { - var textureArray = new ThreadedTextureArray(this); + ThreadedTextureArray textureArray = new(this); New()->Set(Ref(textureArray), size, isBuffer); QueueCommand(); @@ -414,7 +414,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public unsafe IProgram LoadProgramBinary(byte[] programBinary, bool hasFragmentShader, ShaderInfo info) { - var program = new ThreadedProgram(this); + ThreadedProgram program = new(this); BinaryProgramRequest request = new(program, programBinary, hasFragmentShader, info); Programs.Add(request); diff --git a/src/Ryujinx.Graphics.GAL/ResourceLayout.cs b/src/Ryujinx.Graphics.GAL/ResourceLayout.cs index 91f74e907..7731d5683 100644 --- a/src/Ryujinx.Graphics.GAL/ResourceLayout.cs +++ b/src/Ryujinx.Graphics.GAL/ResourceLayout.cs @@ -126,7 +126,7 @@ namespace Ryujinx.Graphics.GAL if (Descriptors != null) { - foreach (var descriptor in Descriptors) + foreach (ResourceDescriptor descriptor in Descriptors) { hasher.Add(descriptor); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs index cd8144724..0784fdca8 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs @@ -2,6 +2,7 @@ using Ryujinx.Graphics.Device; using Ryujinx.Graphics.Gpu.Engine.InlineToMemory; using Ryujinx.Graphics.Gpu.Engine.Threed; using Ryujinx.Graphics.Gpu.Engine.Types; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Shader; using System; @@ -90,7 +91,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute /// Method call argument private void SendSignalingPcasB(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; // Since we're going to change the state, make sure any pending instanced draws are done. _3dEngine.PerformDeferredDraws(); @@ -100,7 +101,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute uint qmdAddress = _state.State.SendPcasA; - var qmd = _channel.MemoryManager.Read((ulong)qmdAddress << 8); + ComputeQmd qmd = _channel.MemoryManager.Read((ulong)qmdAddress << 8); ulong shaderGpuVa = ((ulong)_state.State.SetProgramRegionAAddressUpper << 32) | _state.State.SetProgramRegionB; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs b/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs index 1bce5ce2d..7040e2fca 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Gpu.Engine [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteWithRedundancyCheck(int offset, int value, out bool changed) { - var shadowRamControl = _state.State.SetMmeShadowRamControlMode; + SetMmeShadowRamControlMode shadowRamControl = _state.State.SetMmeShadowRamControlMode; if (shadowRamControl == SetMmeShadowRamControlMode.MethodPassthrough || offset < 0x200) { _state.WriteWithRedundancyCheck(offset, value, out changed); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs index cdeae0040..19b90c59a 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma /// The LaunchDma call argument private void DmaCopy(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; CopyFlags copyFlags = (CopyFlags)argument; @@ -225,8 +225,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma int srcBpp = remap ? srcComponents * componentSize : 1; int dstBpp = remap ? dstComponents * componentSize : 1; - var dst = Unsafe.As(ref _state.State.SetDstBlockSize); - var src = Unsafe.As(ref _state.State.SetSrcBlockSize); + DmaTexture dst = Unsafe.As(ref _state.State.SetDstBlockSize); + DmaTexture src = Unsafe.As(ref _state.State.SetSrcBlockSize); int srcRegionX = 0, srcRegionY = 0, dstRegionX = 0, dstRegionY = 0; @@ -245,7 +245,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma int srcStride = (int)_state.State.PitchIn; int dstStride = (int)_state.State.PitchOut; - var srcCalculator = new OffsetCalculator( + OffsetCalculator srcCalculator = new( src.Width, src.Height, srcStride, @@ -254,7 +254,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma src.MemoryLayout.UnpackGobBlocksInZ(), srcBpp); - var dstCalculator = new OffsetCalculator( + OffsetCalculator dstCalculator = new( dst.Width, dst.Height, dstStride, @@ -293,7 +293,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma if (completeSource && completeDest && !srcLinear && isIdentityRemap) { - var source = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture source = memoryManager.Physical.TextureCache.FindTexture( memoryManager, srcGpuVa, srcBpp, @@ -309,7 +309,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma { source.SynchronizeMemory(); - var target = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, source.Info.FormatInfo, dstGpuVa, @@ -339,7 +339,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma if (completeSource && completeDest && !(dstLinear && !srcLinear) && isIdentityRemap) { - var target = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindTexture( memoryManager, dstGpuVa, dstBpp, diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs index 984a9cff8..c0f8ccf76 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs @@ -159,7 +159,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo int availableCount = commandBuffer.Length - offset; int consumeCount = Math.Min(_state.MethodCount, availableCount); - var data = commandBuffer.Slice(offset, consumeCount); + ReadOnlySpan data = commandBuffer.Slice(offset, consumeCount); if (_state.SubChannel == 0) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs index 78099f74a..37d7457fc 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs @@ -1,6 +1,7 @@ using Ryujinx.Common; using Ryujinx.Common.Memory; using Ryujinx.Graphics.Device; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using System; using System.Collections.Generic; @@ -168,9 +169,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory /// private void FinishTransfer() { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; - var data = MemoryMarshal.Cast(_buffer)[.._size]; + Span data = MemoryMarshal.Cast(_buffer)[.._size]; if (_isLinear && _lineCount == 1) { @@ -184,7 +185,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory // Right now the copy code at the bottom assumes that it is used on both which might be incorrect. if (!_isLinear) { - var target = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindTexture( memoryManager, _dstGpuVa, 1, @@ -199,7 +200,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory if (target != null) { target.SynchronizeMemory(); - var dataCopy = MemoryOwner.RentCopy(data); + MemoryOwner dataCopy = MemoryOwner.RentCopy(data); target.SetData(dataCopy, 0, 0, new GAL.Rectangle(_dstX, _dstY, _lineLengthIn / target.Info.FormatInfo.BytesPerPixel, _lineCount)); target.SignalModified(); @@ -207,7 +208,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory } } - var dstCalculator = new OffsetCalculator( + OffsetCalculator dstCalculator = new( _dstWidth, _dstHeight, _dstStride, diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs index 51d15eac8..9ad62ce6d 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs @@ -287,12 +287,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawArraysInstanced(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); if (ShouldSkipDraw(state, instanceCount.Word)) { @@ -316,13 +316,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElements(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var indexAddressHigh = FetchParam(); - var indexAddressLow = FetchParam(); - var indexType = FetchParam(); - var firstIndex = 0; - var indexCount = FetchParam(); + FifoWord indexAddressHigh = FetchParam(); + FifoWord indexAddressLow = FetchParam(); + FifoWord indexType = FetchParam(); + int firstIndex = 0; + FifoWord indexCount = FetchParam(); _processor.ThreedClass.UpdateIndexBuffer( (uint)indexAddressHigh.Word, @@ -346,13 +346,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElementsInstanced(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); if (ShouldSkipDraw(state, instanceCount.Word)) { @@ -376,17 +376,17 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElementsIndirect(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); ulong indirectBufferGpuVa = count.GpuVa; - var bufferCache = _processor.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _processor.MemoryManager.Physical.BufferCache; bool useBuffer = bufferCache.CheckModified(_processor.MemoryManager, indirectBufferGpuVa, IndirectIndexedDataEntrySize, out ulong indirectBufferAddress); @@ -434,7 +434,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME int startDraw = arg0; int endDraw = arg1; - var topology = (PrimitiveTopology)arg2; + PrimitiveTopology topology = (PrimitiveTopology)arg2; int paddingWords = arg3; int stride = paddingWords * 4 + 0x14; @@ -470,12 +470,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME for (int i = 0; i < maxDrawCount; i++) { - var count = FetchParam(); + FifoWord count = FetchParam(); #pragma warning disable IDE0059 // Remove unnecessary value assignment - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); #pragma warning restore IDE0059 if (i == 0) @@ -494,7 +494,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME } } - var bufferCache = _processor.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _processor.MemoryManager.Physical.BufferCache; ulong indirectBufferSize = (ulong)maxDrawCount * (ulong)stride; @@ -528,7 +528,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or a 0 value with null address if the FIFO is empty private FifoWord FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs index 5818bb6cc..217812245 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs @@ -90,13 +90,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// True if there is a implementation available and supported, false otherwise public static bool TryGetMacroHLEFunction(ReadOnlySpan code, Capabilities caps, out MacroHLEFunctionName name) { - var mc = MemoryMarshal.Cast(code); + ReadOnlySpan mc = MemoryMarshal.Cast(code); for (int i = 0; i < _table.Length; i++) { - ref var entry = ref _table[i]; + ref TableEntry entry = ref _table[i]; - var hash = XXHash128.ComputeHash(mc[..entry.Length]); + Hash128 hash = XXHash128.ComputeHash(mc[..entry.Length]); if (hash == entry.Hash) { if (IsMacroHLESupported(caps, entry.Name)) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs index dd60688d6..707265184 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs @@ -369,7 +369,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or 0 if the FIFO is empty private int FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs index 01bff8e89..174af9739 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or 0 if the FIFO is empty public int FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs index b5a42349c..8fef022d2 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender sb.AppendLine($"private static Dictionary _entries = new()"); sb.AppendLine("{"); - foreach (var entry in Table) + foreach (AdvancedBlendUcode entry in Table) { Hash128 hash = XXHash128.ComputeHash(MemoryMarshal.Cast(entry.Code)); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs index 49cd2d96a..9a24710fd 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs @@ -66,7 +66,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender descriptor = default; - if (!AdvancedBlendPreGenTable.Entries.TryGetValue(hash, out var entry)) + if (!AdvancedBlendPreGenTable.Entries.TryGetValue(hash, out AdvancedBlendEntry entry)) { return false; } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs index 6de50fb2e..eba1b6030 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw { if (disposing) { - foreach (var texture in _cache.Values) + foreach (ITexture texture in _cache.Values) { texture.Release(); } @@ -620,7 +620,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw DestroyIfNotNull(ref _geometryIndexDataBuffer.Handle); DestroyIfNotNull(ref _sequentialIndexBuffer); - foreach (var indexBuffer in _topologyRemapBuffers.Values) + foreach (IndexBuffer indexBuffer in _topologyRemapBuffers.Values) { _context.Renderer.DeleteBuffer(indexBuffer.Handle); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs index e0ecb45f8..11481277d 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs @@ -132,7 +132,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw for (int index = 0; index < Constants.TotalVertexAttribs; index++) { - var vertexAttrib = vertexAttribStateSpan[index]; + VertexAttribState vertexAttrib = vertexAttribStateSpan[index]; if (!FormatTable.TryGetSingleComponentAttribFormat(vertexAttrib.UnpackFormat(), out Format format, out int componentsCount)) { @@ -159,7 +159,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw int bufferIndex = vertexAttrib.UnpackBufferIndex(); GpuVa endAddress = vertexBufferEndAddressSpan[bufferIndex]; - var vertexBuffer = vertexBufferStateSpan[bufferIndex]; + VertexBufferState vertexBuffer = vertexBufferStateSpan[bufferIndex]; bool instanced = vertexBufferInstancedSpan[bufferIndex]; ulong address = vertexBuffer.Address.Pack(); @@ -373,7 +373,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw /// Size of the buffer in bytes private readonly void SetBufferTexture(ResourceReservations reservations, int index, Format format, ulong address, ulong size) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; BufferRange range = memoryManager.Physical.BufferCache.GetBufferRange(memoryManager.GetPhysicalRegions(address, size), BufferStage.VertexBuffer); @@ -414,7 +414,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw indexOffset <<= shift; size <<= shift; - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; ulong misalign = address & ((ulong)_context.Capabilities.TextureBufferOffsetAlignment - 1); BufferRange range = memoryManager.Physical.BufferCache.GetBufferRange( diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs index 2095fcd7a..6fc49fc8d 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs @@ -1,3 +1,4 @@ +using Ryujinx.Graphics.Gpu.Memory; using System; using System.Runtime.InteropServices; @@ -92,7 +93,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (enable) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack(); @@ -111,7 +112,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (_ubFollowUpAddress != 0) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; Span data = MemoryMarshal.Cast(_ubData.AsSpan(0, (int)(_ubByteCount / 4))); @@ -131,7 +132,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// New uniform buffer data word public void Update(int argument) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack() + (uint)uniformBuffer.Offset; @@ -157,7 +158,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Data to be written to the uniform buffer public void Update(ReadOnlySpan data) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack() + (uint)uniformBuffer.Offset; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs index ff499d736..f9fb20cfb 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs @@ -471,7 +471,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int textureId = _state.State.DrawTextureTextureId; int samplerId = _state.State.DrawTextureSamplerId; - (var texture, var sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId); + (Image.Texture texture, Sampler sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId); srcX0 *= texture.ScaleFactor; srcY0 *= texture.ScaleFactor; @@ -684,8 +684,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (hasCount) { - var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); - var parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferRange, BufferStage.Indirect); + BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); + BufferRange parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferRange, BufferStage.Indirect); if (indexed) { @@ -698,7 +698,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed } else { - var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); + BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); if (indexed) { @@ -820,7 +820,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed // If there is a mismatch on the host clip region and the one explicitly defined by the guest // on the screen scissor state, then we need to force only one texture to be bound to avoid // host clipping. - var screenScissorState = _state.State.ScreenScissorState; + ScreenScissorState screenScissorState = _state.State.ScreenScissorState; Span scissorStateSpan = _state.State.ScissorState.AsSpan(); @@ -835,7 +835,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (fullClear && clearAffectedByScissor && scissorStateSpan[0].Enable) { - ref var scissorState = ref scissorStateSpan[0]; + ref ScissorState scissorState = ref scissorStateSpan[0]; fullClear = scissorState.X1 == screenScissorState.X && scissorState.Y1 == screenScissorState.Y && @@ -893,7 +893,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (clearAffectedByScissor && scissorStateSpan[0].Enable) { - ref var scissorState = ref scissorStateSpan[0]; + ref ScissorState scissorState = ref scissorStateSpan[0]; scissorX = Math.Max(scissorX, scissorState.X1); scissorY = Math.Max(scissorY, scissorState.Y1); @@ -922,7 +922,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (componentMask != 0) { - var clearColor = _state.State.ClearColors; + ClearColors clearColor = _state.State.ClearColors; ColorF color = new(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs index 3f5af214e..c0e80c894 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs @@ -289,7 +289,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { int rtIndex = rtControl.UnpackPermutationIndex(index); - var colorState = state[rtIndex]; + RtColorState colorState = state[rtIndex]; if (index < count && StateUpdater.IsRtEnabled(colorState)) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs index 746f566ad..3e77eb8ac 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Numerics; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -57,13 +58,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _registerToGroupMapping = new byte[BlockSize]; _callbacks = new Action[entries.Length]; - var fieldToDelegate = new Dictionary(); + Dictionary fieldToDelegate = new(); for (int entryIndex = 0; entryIndex < entries.Length; entryIndex++) { - var entry = entries[entryIndex]; + StateUpdateCallbackEntry entry = entries[entryIndex]; - foreach (var fieldName in entry.FieldNames) + foreach (string fieldName in entry.FieldNames) { fieldToDelegate.Add(fieldName, entryIndex); } @@ -71,15 +72,15 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _callbacks[entryIndex] = entry.Callback; } - var fields = typeof(TState).GetFields(); + FieldInfo[] fields = typeof(TState).GetFields(); int offset = 0; for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++) { - var field = fields[fieldIndex]; + FieldInfo field = fields[fieldIndex]; - var currentFieldOffset = (int)Marshal.OffsetOf(field.Name); - var nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); + int currentFieldOffset = (int)Marshal.OffsetOf(field.Name); + int nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); int sizeOfField = nextFieldOffset - currentFieldOffset; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs index 37db8cb70..46d724bf5 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Engine.Threed.Blender; using Ryujinx.Graphics.Gpu.Engine.Types; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Texture; @@ -464,8 +465,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// If this is not -1, it indicates that only the given indexed target will be used. public void UpdateRenderTargetState(RenderTargetUpdateFlags updateFlags, int singleUse = -1) { - var memoryManager = _channel.MemoryManager; - var rtControl = _state.State.RtControl; + MemoryManager memoryManager = _channel.MemoryManager; + RtControl rtControl = _state.State.RtControl; bool useControl = (updateFlags & RenderTargetUpdateFlags.UseControl) == RenderTargetUpdateFlags.UseControl; bool layered = (updateFlags & RenderTargetUpdateFlags.Layered) == RenderTargetUpdateFlags.Layered; @@ -474,12 +475,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int count = useControl ? rtControl.UnpackCount() : Constants.TotalRenderTargets; - var msaaMode = _state.State.RtMsaaMode; + TextureMsaaMode msaaMode = _state.State.RtMsaaMode; int samplesInX = msaaMode.SamplesInX(); int samplesInY = msaaMode.SamplesInY(); - var scissor = _state.State.ScreenScissorState; + ScreenScissorState scissor = _state.State.ScreenScissorState; Size sizeHint = new((scissor.X + scissor.Width) * samplesInX, (scissor.Y + scissor.Height) * samplesInY, 1); int clipRegionWidth = int.MaxValue; @@ -494,7 +495,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { int rtIndex = useControl ? rtControl.UnpackPermutationIndex(index) : index; - var colorState = rtColorStateSpan[rtIndex]; + RtColorState colorState = rtColorStateSpan[rtIndex]; if (index >= count || !IsRtEnabled(colorState) || (singleColor && index != singleUse)) { @@ -544,8 +545,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (dsEnable && (updateFlags & RenderTargetUpdateFlags.UpdateDepthStencil) == RenderTargetUpdateFlags.UpdateDepthStencil) { - var dsState = _state.State.RtDepthStencilState; - var dsSize = _state.State.RtDepthStencilSize; + RtDepthStencilState dsState = _state.State.RtDepthStencilState; + Size3D dsSize = _state.State.RtDepthStencilSize; depthStencil = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, @@ -647,7 +648,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if ((_state.State.YControl & YControl.NegateY) != 0) { - ref var screenScissor = ref _state.State.ScreenScissorState; + ref ScreenScissorState screenScissor = ref _state.State.ScreenScissorState; y = screenScissor.Height - height - y; if (y < 0) @@ -725,8 +726,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateViewportTransform() { - var yControl = _state.State.YControl; - var face = _state.State.FaceState; + YControl yControl = _state.State.YControl; + FaceState face = _state.State.FaceState; bool disableTransform = _state.State.ViewportTransformEnable == 0; bool yNegate = (yControl & YControl.NegateY) != 0; @@ -742,17 +743,17 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (disableTransform) { - ref var scissor = ref _state.State.ScreenScissorState; + ref ScreenScissorState scissor = ref _state.State.ScreenScissorState; float rScale = _channel.TextureManager.RenderTargetScale; - var scissorRect = new Rectangle(0, 0, (scissor.X + scissor.Width) * rScale, (scissor.Y + scissor.Height) * rScale); + Rectangle scissorRect = new(0, 0, (scissor.X + scissor.Width) * rScale, (scissor.Y + scissor.Height) * rScale); viewports[index] = new Viewport(scissorRect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, ViewportSwizzle.PositiveZ, ViewportSwizzle.PositiveW, 0, 1); continue; } - ref var transform = ref viewportTransformSpan[index]; - ref var extents = ref viewportExtentsSpan[index]; + ref ViewportTransform transform = ref viewportTransformSpan[index]; + ref ViewportExtents extents = ref viewportExtentsSpan[index]; float scaleX = MathF.Abs(transform.ScaleX); float scaleY = transform.ScaleY; @@ -847,7 +848,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateDepthBiasState() { - var depthBias = _state.State.DepthBiasState; + DepthBiasState depthBias = _state.State.DepthBiasState; float factor = _state.State.DepthBiasFactor; float units = _state.State.DepthBiasUnits; @@ -868,9 +869,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateStencilTestState() { - var backMasks = _state.State.StencilBackMasks; - var test = _state.State.StencilTestState; - var backTest = _state.State.StencilBackTestState; + StencilBackMasks backMasks = _state.State.StencilBackMasks; + StencilTestState test = _state.State.StencilTestState; + StencilBackTestState backTest = _state.State.StencilBackTestState; CompareOp backFunc; StencilOp backSFail; @@ -940,10 +941,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateSamplerPoolState() { - var texturePool = _state.State.TexturePoolState; - var samplerPool = _state.State.SamplerPoolState; + PoolState texturePool = _state.State.TexturePoolState; + PoolState samplerPool = _state.State.SamplerPoolState; - var samplerIndex = _state.State.SamplerIndex; + SamplerIndex samplerIndex = _state.State.SamplerIndex; int maximumId = samplerIndex == SamplerIndex.ViaHeaderIndex ? texturePool.MaximumId @@ -957,7 +958,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateTexturePoolState() { - var texturePool = _state.State.TexturePoolState; + PoolState texturePool = _state.State.TexturePoolState; _channel.TextureManager.SetGraphicsTexturePool(texturePool.Address.Pack(), texturePool.MaximumId); _channel.TextureManager.SetGraphicsTextureBufferIndex((int)_state.State.TextureBufferIndex); @@ -978,7 +979,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalVertexAttribs; index++) { - var vertexAttrib = vertexAttribStateSpan[index]; + VertexAttribState vertexAttrib = vertexAttribStateSpan[index]; int bufferIndex = vertexAttrib.UnpackBufferIndex(); @@ -1072,7 +1073,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateIndexBufferState() { - var indexBuffer = _state.State.IndexBufferState; + IndexBufferState indexBuffer = _state.State.IndexBufferState; if (_drawState.IndexCount == 0) { @@ -1121,7 +1122,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalVertexBuffers; index++) { - var vertexBuffer = vertexBufferStateSpan[index]; + VertexBufferState vertexBuffer = vertexBufferStateSpan[index]; if (!vertexBuffer.UnpackEnable()) { @@ -1205,8 +1206,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateFaceState() { - var yControl = _state.State.YControl; - var face = _state.State.FaceState; + YControl yControl = _state.State.YControl; + FaceState face = _state.State.FaceState; _pipeline.CullEnable = face.CullEnable; _pipeline.CullMode = face.CullFace; @@ -1247,7 +1248,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalRenderTargets; index++) { - var colorMask = rtColorMaskSpan[rtColorMaskShared ? 0 : index]; + RtColorMask colorMask = rtColorMaskSpan[rtColorMaskShared ? 0 : index]; uint componentMask; @@ -1270,7 +1271,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (_state.State.BlendUcodeEnable != BlendUcodeEnable.Disabled) { - if (_context.Capabilities.SupportsBlendEquationAdvanced && _blendManager.TryGetAdvancedBlend(out var blendDescriptor)) + if (_context.Capabilities.SupportsBlendEquationAdvanced && _blendManager.TryGetAdvancedBlend(out AdvancedBlendDescriptor blendDescriptor)) { // Try to HLE it using advanced blend on the host if we can. _context.Renderer.Pipeline.SetBlendState(blendDescriptor); @@ -1296,9 +1297,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalRenderTargets; index++) { bool enable = blendEnableSpan[index]; - var blend = blendStateSpan[index]; + BlendState blend = blendStateSpan[index]; - var descriptor = new BlendDescriptor( + BlendDescriptor descriptor = new( enable, blendConstant, blend.ColorOp, @@ -1324,9 +1325,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed else { bool enable = _state.State.BlendEnable[0]; - var blend = _state.State.BlendStateCommon; + BlendStateCommon blend = _state.State.BlendStateCommon; - var descriptor = new BlendDescriptor( + BlendDescriptor descriptor = new( enable, blendConstant, blend.ColorOp, @@ -1429,7 +1430,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateShaderState() { - var shaderCache = _channel.MemoryManager.Physical.ShaderCache; + ShaderCache shaderCache = _channel.MemoryManager.Physical.ShaderCache; _vtgWritesRtLayer = false; @@ -1441,7 +1442,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < 6; index++) { - var shader = shaderStateSpan[index]; + ShaderState shader = shaderStateSpan[index]; if (!shader.UnpackEnable() && index != 1) { continue; @@ -1546,7 +1547,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateSupportBufferViewportSize() { - ref var transform = ref _state.State.ViewportTransform[0]; + ref ViewportTransform transform = ref _state.State.ViewportTransform[0]; float scaleX = MathF.Abs(transform.ScaleX); float scaleY = transform.ScaleY; @@ -1585,8 +1586,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Current depth mode private DepthMode GetDepthMode() { - ref var transform = ref _state.State.ViewportTransform[0]; - ref var extents = ref _state.State.ViewportExtents[0]; + ref ViewportTransform transform = ref _state.State.ViewportTransform[0]; + ref ViewportExtents extents = ref _state.State.ViewportExtents[0]; DepthMode depthMode; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs index 5e1f1c332..99cd0c2b2 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs @@ -81,8 +81,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _i2mClass = new InlineToMemoryClass(context, channel, initializeState: false); - var spec = new SpecializationStateUpdater(context); - var drawState = new DrawState(); + SpecializationStateUpdater spec = new(context); + DrawState drawState = new(); _drawManager = new DrawManager(context, channel, _state, drawState, spec); _blendManager = new AdvancedBlendManager(_state); @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed } else { - var lhsVec = Unsafe.As, ReadOnlySpan>>(ref lhs); - var rhsVec = Unsafe.As, ReadOnlySpan>>(ref rhs); + ReadOnlySpan> lhsVec = Unsafe.As, ReadOnlySpan>>(ref lhs); + ReadOnlySpan> rhsVec = Unsafe.As, ReadOnlySpan>>(ref rhs); return Vector128.EqualsAll(lhsVec[0], rhsVec[0]) && Vector128.EqualsAll(lhsVec[1], rhsVec[1]); @@ -266,8 +266,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Blend enable public void UpdateBlendEnable(Span enable) { - var shadow = ShadowMode; - var state = _state.State.BlendEnable.AsSpan(); + SetMmeShadowRamControlMode shadow = ShadowMode; + Span state = _state.State.BlendEnable.AsSpan(); if (shadow.IsReplay()) { @@ -293,8 +293,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Color masks public void UpdateColorMasks(Span masks) { - var shadow = ShadowMode; - var state = _state.State.RtColorMask.AsSpan(); + SetMmeShadowRamControlMode shadow = ShadowMode; + Span state = _state.State.RtColorMask.AsSpan(); if (shadow.IsReplay()) { @@ -322,12 +322,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Type of the binding public void UpdateIndexBuffer(uint addrHigh, uint addrLow, IndexType type) { - var shadow = ShadowMode; - ref var state = ref _state.State.IndexBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref IndexBufferState state = ref _state.State.IndexBufferState; if (shadow.IsReplay()) { - ref var shadowState = ref _state.ShadowState.IndexBufferState; + ref IndexBufferState shadowState = ref _state.ShadowState.IndexBufferState; addrHigh = shadowState.Address.High; addrLow = shadowState.Address.Low; type = shadowState.Type; @@ -344,7 +344,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (shadow.IsTrack()) { - ref var shadowState = ref _state.ShadowState.IndexBufferState; + ref IndexBufferState shadowState = ref _state.ShadowState.IndexBufferState; shadowState.Address.High = addrHigh; shadowState.Address.Low = addrLow; shadowState.Type = type; @@ -359,12 +359,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Low part of the address public void UpdateUniformBufferState(int size, uint addrHigh, uint addrLow) { - var shadow = ShadowMode; - ref var state = ref _state.State.UniformBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref UniformBufferState state = ref _state.State.UniformBufferState; if (shadow.IsReplay()) { - ref var shadowState = ref _state.ShadowState.UniformBufferState; + ref UniformBufferState shadowState = ref _state.ShadowState.UniformBufferState; size = shadowState.Size; addrHigh = shadowState.Address.High; addrLow = shadowState.Address.Low; @@ -376,7 +376,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (shadow.IsTrack()) { - ref var shadowState = ref _state.ShadowState.UniformBufferState; + ref UniformBufferState shadowState = ref _state.ShadowState.UniformBufferState; shadowState.Size = size; shadowState.Address.High = addrHigh; shadowState.Address.Low = addrLow; @@ -390,8 +390,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Offset to update with public void SetShaderOffset(int index, uint offset) { - var shadow = ShadowMode; - ref var shaderState = ref _state.State.ShaderState[index]; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref ShaderState shaderState = ref _state.State.ShaderState[index]; if (shadow.IsReplay()) { @@ -417,8 +417,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Uniform buffer state public void UpdateUniformBufferState(UniformBufferState ubState) { - var shadow = ShadowMode; - ref var state = ref _state.State.UniformBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref UniformBufferState state = ref _state.State.UniformBufferState; if (shadow.IsReplay()) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs index 0dd9481df..5ab58d7d1 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.Device; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Engine.Types; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using Ryujinx.Memory; using System; @@ -123,7 +124,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Bytes per pixel private void UnscaledFullCopy(TwodTexture src, TwodTexture dst, int w, int h, int bpp) { - var srcCalculator = new OffsetCalculator( + OffsetCalculator srcCalculator = new( w, h, src.Stride, @@ -134,7 +135,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod (int _, int srcSize) = srcCalculator.GetRectangleRange(0, 0, w, h); - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; ulong srcGpuVa = src.Address.Pack(); ulong dstGpuVa = dst.Address.Pack(); @@ -228,10 +229,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Method call argument private void PixelsFromMemorySrcY0Int(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; - var dstCopyTexture = Unsafe.As(ref _state.State.SetDstFormat); - var srcCopyTexture = Unsafe.As(ref _state.State.SetSrcFormat); + TwodTexture dstCopyTexture = Unsafe.As(ref _state.State.SetDstFormat); + TwodTexture srcCopyTexture = Unsafe.As(ref _state.State.SetSrcFormat); long srcX = ((long)_state.State.SetPixelsFromMemorySrcX0Int << 32) | (long)(ulong)_state.State.SetPixelsFromMemorySrcX0Frac; long srcY = ((long)_state.State.PixelsFromMemorySrcY0Int << 32) | (long)(ulong)_state.State.SetPixelsFromMemorySrcY0Frac; @@ -268,10 +269,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod // The source and destination textures should at least be as big as the region being requested. // The hints will only resize within alignment constraints, so out of bound copies won't resize in most cases. - var srcHint = new Size(srcX2, srcY2, 1); - var dstHint = new Size(dstX2, dstY2, 1); + Size srcHint = new(srcX2, srcY2, 1); + Size dstHint = new(dstX2, dstY2, 1); - var srcCopyTextureFormat = srcCopyTexture.Format.Convert(); + FormatInfo srcCopyTextureFormat = srcCopyTexture.Format.Convert(); int srcWidthAligned = srcCopyTexture.Stride / srcCopyTextureFormat.BytesPerPixel; @@ -304,7 +305,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod // are the same, as we can't blit between different depth formats. bool srcDepthAlias = srcCopyTexture.Format == dstCopyTexture.Format; - var srcTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture srcTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, srcCopyTexture, offset, @@ -341,7 +342,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod dstCopyTextureFormat = dstCopyTexture.Format.Convert(); } - var dstTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture dstTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, dstCopyTexture, 0, diff --git a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs index 33618a15b..047cbcca6 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu /// The new memory manager to be bound public void BindMemory(MemoryManager memoryManager) { - var oldMemoryManager = Interlocked.Exchange(ref _memoryManager, memoryManager ?? throw new ArgumentNullException(nameof(memoryManager))); + MemoryManager oldMemoryManager = Interlocked.Exchange(ref _memoryManager, memoryManager ?? throw new ArgumentNullException(nameof(memoryManager))); memoryManager.Physical.IncrementReferenceCount(); @@ -85,7 +85,7 @@ namespace Ryujinx.Graphics.Gpu { TextureManager.ReloadPools(); - var memoryManager = Volatile.Read(ref _memoryManager); + MemoryManager memoryManager = Volatile.Read(ref _memoryManager); memoryManager?.Physical.BufferCache.QueuePrune(); } @@ -138,7 +138,7 @@ namespace Ryujinx.Graphics.Gpu _processor.Dispose(); TextureManager.Dispose(); - var oldMemoryManager = Interlocked.Exchange(ref _memoryManager, null); + MemoryManager oldMemoryManager = Interlocked.Exchange(ref _memoryManager, null); if (oldMemoryManager != null) { oldMemoryManager.Physical.BufferCache.NotifyBuffersModified -= BufferManager.Rebind; diff --git a/src/Ryujinx.Graphics.Gpu/GpuContext.cs b/src/Ryujinx.Graphics.Gpu/GpuContext.cs index 2eee73784..db4b54ab0 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuContext.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuContext.cs @@ -157,7 +157,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown when is invalid public MemoryManager CreateMemoryManager(ulong pid, ulong cpuMemorySize) { - if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid)); } @@ -173,7 +173,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown when is invalid public DeviceMemoryManager CreateDeviceMemoryManager(ulong pid) { - if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid)); } @@ -189,7 +189,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown if was already registered public void RegisterProcess(ulong pid, Cpu.IVirtualMemoryManagerTracked cpuMemory) { - var physicalMemory = new PhysicalMemory(this, cpuMemory); + PhysicalMemory physicalMemory = new(this, cpuMemory); if (!PhysicalMemoryRegistry.TryAdd(pid, physicalMemory)) { throw new ArgumentException("The PID was already registered", nameof(pid)); @@ -204,7 +204,7 @@ namespace Ryujinx.Graphics.Gpu /// ID of the process public void UnregisterProcess(ulong pid) { - if (PhysicalMemoryRegistry.TryRemove(pid, out var physicalMemory)) + if (PhysicalMemoryRegistry.TryRemove(pid, out PhysicalMemory physicalMemory)) { physicalMemory.ShaderCache.ShaderCacheStateChanged -= ShaderCacheStateUpdate; physicalMemory.Dispose(); @@ -279,7 +279,7 @@ namespace Ryujinx.Graphics.Gpu { HostInitalized.WaitOne(); - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.ShaderCache.Initialize(cancellationToken); } @@ -319,7 +319,7 @@ namespace Ryujinx.Graphics.Gpu /// public void ProcessShaderCacheQueue() { - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.ShaderCache.ProcessShaderCacheQueue(); } @@ -402,7 +402,7 @@ namespace Ryujinx.Graphics.Gpu } } - foreach (var action in SyncpointActions) + foreach (ISyncActionHandler action in SyncpointActions) { action.SyncPreAction(syncPoint); } @@ -456,7 +456,7 @@ namespace Ryujinx.Graphics.Gpu _gpuReadyEvent.Dispose(); // Has to be disposed before processing deferred actions, as it will produce some. - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.Dispose(); } diff --git a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs index 7ba74fd00..032d5339f 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// The texture if found, null otherwise public Texture FindShortCache(in TextureDescriptor descriptor) { - if (_shortCacheLookup.Count > 0 && _shortCacheLookup.TryGetValue(descriptor, out var entry)) + if (_shortCacheLookup.Count > 0 && _shortCacheLookup.TryGetValue(descriptor, out ShortTextureCacheEntry entry)) { if (entry.InvalidatedSequence == entry.Texture.InvalidatedSequence) { @@ -267,7 +267,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Last used texture descriptor public void AddShortCache(Texture texture, ref TextureDescriptor descriptor) { - var entry = new ShortTextureCacheEntry(descriptor, texture); + ShortTextureCacheEntry entry = new(descriptor, texture); _shortCacheBuilder.Add(entry); _shortCacheLookup.Add(entry.Descriptor, entry); @@ -286,7 +286,7 @@ namespace Ryujinx.Graphics.Gpu.Image { if (texture.ShortCacheEntry != null) { - var entry = new ShortTextureCacheEntry(texture); + ShortTextureCacheEntry entry = new(texture); _shortCacheBuilder.Add(entry); @@ -304,7 +304,7 @@ namespace Ryujinx.Graphics.Gpu.Image { HashSet toRemove = _shortCache; - foreach (var entry in toRemove) + foreach (ShortTextureCacheEntry entry in toRemove) { entry.Texture.DecrementReferenceCount(); diff --git a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs index 085d72e3d..d2e747564 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs @@ -706,7 +706,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// True if the format is valid, false otherwise public static bool TryGetSingleComponentAttribFormat(uint encoded, out Format format, out int componentsCount) { - bool result = _singleComponentAttribFormats.TryGetValue((VertexAttributeFormat)encoded, out var tuple); + bool result = _singleComponentAttribFormats.TryGetValue((VertexAttributeFormat)encoded, out (Format, int) tuple); format = tuple.Item1; componentsCount = tuple.Item2; diff --git a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs index c4215f196..a3d003649 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs @@ -536,7 +536,7 @@ namespace Ryujinx.Graphics.Gpu.Image // All views must be recreated against the new storage. - foreach (var view in _views) + foreach (Texture view in _views) { Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format}."); view.ScaleFactor = scale; @@ -553,7 +553,7 @@ namespace Ryujinx.Graphics.Gpu.Image { ScaleMode = newScaleMode; - foreach (var view in _views) + foreach (Texture view in _views) { view.ScaleMode = newScaleMode; } @@ -899,7 +899,7 @@ namespace Ryujinx.Graphics.Gpu.Image { using (result) { - var converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Span, width); + MemoryOwner converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Span, width); if (_context.Capabilities.SupportsR4G4B4A4Format) { @@ -1646,7 +1646,7 @@ namespace Ryujinx.Graphics.Gpu.Image { lock (_poolOwners) { - foreach (var owner in _poolOwners) + foreach (TexturePoolOwner owner in _poolOwners) { owner.Pool.ForceRemove(this, owner.ID, deferred); } @@ -1676,7 +1676,7 @@ namespace Ryujinx.Graphics.Gpu.Image { ulong address = 0; - foreach (var owner in _poolOwners) + foreach (TexturePoolOwner owner in _poolOwners) { if (address == 0 || address == owner.GpuAddress) { diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs index a34392d5d..72de7ccf2 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs @@ -128,7 +128,7 @@ namespace Ryujinx.Graphics.Gpu.Image // Any texture that has been unmapped at any point or is partially unmapped // should update their pool references after the remap completes. - foreach (var texture in _partiallyMappedTextures) + foreach (Texture texture in _partiallyMappedTextures) { texture.UpdatePoolMappings(); } @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Gpu.Image for (int i = 0; i < overlapCount; i++) { - var other = _textureOverlaps[i]; + Texture other = _textureOverlaps[i]; if (texture != other && (texture.IsViewCompatible(other.Info, other.Range, true, other.LayerSize, _context.Capabilities, out _, out _) != TextureViewCompatibility.Incompatible || @@ -486,7 +486,7 @@ namespace Ryujinx.Graphics.Gpu.Image int layerSize = !isLinear ? colorState.LayerSize * 4 : 0; - var flags = TextureSearchFlags.WithUpscale; + TextureSearchFlags flags = TextureSearchFlags.WithUpscale; if (discard) { @@ -560,7 +560,7 @@ namespace Ryujinx.Graphics.Gpu.Image target, formatInfo); - var flags = TextureSearchFlags.WithUpscale; + TextureSearchFlags flags = TextureSearchFlags.WithUpscale; if (discard) { @@ -948,7 +948,7 @@ namespace Ryujinx.Graphics.Gpu.Image bool hasLayerViews = false; bool hasMipViews = false; - var incompatibleOverlaps = new List(); + List incompatibleOverlaps = new(); for (int index = 0; index < overlapsCount; index++) { diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs index 6c9aa85c8..46a7a5b5a 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs @@ -239,7 +239,7 @@ namespace Ryujinx.Graphics.Gpu.Image { bool flushed = false; - foreach (var overlap in _incompatibleOverlaps) + foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps) { flushed |= overlap.Group.Storage.FlushModified(true); } @@ -421,7 +421,7 @@ namespace Ryujinx.Graphics.Gpu.Image { if (_loadNeeded[baseHandle + i]) { - var info = GetHandleInformation(baseHandle + i); + (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) info = GetHandleInformation(baseHandle + i); // Ensure the data for this handle is loaded in the span. if (spanEndIndex <= i - 1) @@ -444,7 +444,7 @@ namespace Ryujinx.Graphics.Gpu.Image } } - var endInfo = spanEndIndex == i ? info : GetHandleInformation(baseHandle + spanEndIndex); + (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) endInfo = spanEndIndex == i ? info : GetHandleInformation(baseHandle + spanEndIndex); spanBase = _allOffsets[info.Index]; int spanLast = _allOffsets[endInfo.Index + endInfo.Layers * endInfo.Levels - 1]; @@ -499,7 +499,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// True if flushes should be tracked, false otherwise private bool ShouldFlushTriggerTracking() { - foreach (var overlap in _incompatibleOverlaps) + foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps) { if (overlap.Group._flushIncompatibleOverlaps) { @@ -659,7 +659,7 @@ namespace Ryujinx.Graphics.Gpu.Image bool canImport = Storage.Info.IsLinear && Storage.Info.Stride >= Storage.Info.Width * Storage.Info.FormatInfo.BytesPerPixel; - var hostPointer = canImport ? _physicalMemory.GetHostPointer(Storage.Range) : 0; + IntPtr hostPointer = canImport ? _physicalMemory.GetHostPointer(Storage.Range) : 0; if (hostPointer != 0 && _context.Renderer.PrepareHostMapping(hostPointer, Storage.Size)) { @@ -1049,7 +1049,7 @@ namespace Ryujinx.Graphics.Gpu.Image int endOffset = _allOffsets[viewEnd] + _sliceSizes[lastLevel]; int size = endOffset - offset; - var result = new List(); + List result = new(); for (int i = 0; i < TextureRange.Count; i++) { @@ -1083,7 +1083,7 @@ namespace Ryujinx.Graphics.Gpu.Image offset = _allOffsets[viewStart]; ulong maxSize = Storage.Size - (ulong)offset; - var groupHandle = new TextureGroupHandle( + TextureGroupHandle groupHandle = new( this, offset, Math.Min(maxSize, (ulong)size), @@ -1190,17 +1190,17 @@ namespace Ryujinx.Graphics.Gpu.Image /// The offset of the old handles in relation to the new ones private void InheritHandles(TextureGroupHandle[] oldHandles, TextureGroupHandle[] handles, int relativeOffset) { - foreach (var group in handles) + foreach (TextureGroupHandle group in handles) { - foreach (var handle in group.Handles) + foreach (RegionHandle handle in group.Handles) { bool dirty = false; - foreach (var oldGroup in oldHandles) + foreach (TextureGroupHandle oldGroup in oldHandles) { if (group.OverlapsWith(oldGroup.Offset + relativeOffset, oldGroup.Size)) { - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { if (handle.OverlapsWith(oldHandle.Address, oldHandle.Size)) { @@ -1224,7 +1224,7 @@ namespace Ryujinx.Graphics.Gpu.Image } } - foreach (var oldGroup in oldHandles) + foreach (TextureGroupHandle oldGroup in oldHandles) { oldGroup.Modified = false; } @@ -1284,7 +1284,7 @@ namespace Ryujinx.Graphics.Gpu.Image continue; } - foreach (var oldGroup in _handles) + foreach (TextureGroupHandle oldGroup in _handles) { if (!groupHandle.OverlapsWith(oldGroup.Offset, oldGroup.Size)) { @@ -1295,7 +1295,7 @@ namespace Ryujinx.Graphics.Gpu.Image { bool hasMatch = false; - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { if (oldHandle.RangeEquals(handle)) { @@ -1322,9 +1322,9 @@ namespace Ryujinx.Graphics.Gpu.Image InheritHandles(_handles, handles, 0); - foreach (var oldGroup in _handles) + foreach (TextureGroupHandle oldGroup in _handles) { - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { oldHandle.Dispose(); } @@ -1350,12 +1350,12 @@ namespace Ryujinx.Graphics.Gpu.Image else if (!(_hasMipViews || _hasLayerViews)) { // Single dirty region. - var cpuRegionHandles = new RegionHandle[TextureRange.Count]; + RegionHandle[] cpuRegionHandles = new RegionHandle[TextureRange.Count]; int count = 0; for (int i = 0; i < TextureRange.Count; i++) { - var currentRange = TextureRange.GetSubRange(i); + MemoryRange currentRange = TextureRange.GetSubRange(i); if (currentRange.Address != MemoryManager.PteUnmapped) { cpuRegionHandles[count++] = GenerateHandle(currentRange.Address, currentRange.Size); @@ -1367,7 +1367,7 @@ namespace Ryujinx.Graphics.Gpu.Image Array.Resize(ref cpuRegionHandles, count); } - var groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles); + TextureGroupHandle groupHandle = new(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles); handles = [groupHandle]; } @@ -1385,7 +1385,7 @@ namespace Ryujinx.Graphics.Gpu.Image if (_is3D) { - var handlesList = new List(); + List handlesList = new(); for (int i = 0; i < levelHandles; i++) { @@ -1468,8 +1468,8 @@ namespace Ryujinx.Graphics.Gpu.Image // Get the location of each texture within its storage, so we can find the handles to apply the dependency to. // This can consist of multiple disjoint regions, for example if this is a mip slice of an array texture. - var targetRange = new List<(int BaseHandle, int RegionCount)>(); - var otherRange = new List<(int BaseHandle, int RegionCount)>(); + List<(int BaseHandle, int RegionCount)> targetRange = new(); + List<(int BaseHandle, int RegionCount)> otherRange = new(); EvaluateRelevantHandles(firstLayer, firstLevel, other.Info.GetSlices(), other.Info.Levels, (baseHandle, regionCount, _, _) => { diff --git a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs index da0a3a1d8..fd9a1e83b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs @@ -120,7 +120,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Texture with the requested format, or null if not found public Texture Find(Format format) { - foreach (var alias in _aliases) + foreach (Alias alias in _aliases) { if (alias.Format == format) { @@ -136,7 +136,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// public void Destroy() { - foreach (var entry in _aliases) + foreach (Alias entry in _aliases) { entry.Texture.DecrementReferenceCount(); } @@ -369,7 +369,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// If true, queue the dereference to happen on the render thread, otherwise dereference immediately public void ForceRemove(Texture texture, int id, bool deferred) { - var previous = Interlocked.Exchange(ref Items[id], null); + Texture previous = Interlocked.Exchange(ref Items[id], null); if (deferred) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs index 16fdb87d7..bb38d7a15 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs @@ -762,7 +762,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { _context.Renderer.BackgroundContextAction(() => { - var ranges = _modifiedRanges; + BufferModifiedRangeList ranges = _modifiedRanges; if (ranges != null) { @@ -877,7 +877,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_virtualDependencies != null) { - foreach (var virtualBuffer in _virtualDependencies) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies) { CopyToDependantVirtualBuffer(virtualBuffer, address, size); } @@ -902,7 +902,7 @@ namespace Ryujinx.Graphics.Gpu.Memory [MethodImpl(MethodImplOptions.NoInlining)] private void CopyFromDependantVirtualBuffersImpl() { - foreach (var virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) { virtualBuffer.ConsumeModifiedRegion(this, (mAddress, mSize) => { @@ -941,7 +941,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { byte[] storage = dataSpan.ToArray(); - foreach (var virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) { virtualBuffer.ConsumeModifiedRegion(address, size, (mAddress, mSize) => { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs index 1f316f3ae..31b1658da 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { // Storage buffer bindings may require special treatment. - var rawStage = stage & BufferStage.StageMask; + BufferStage rawStage = stage & BufferStage.StageMask; if (rawStage == BufferStage.Fragment) { @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Gpu.Memory // Storage write. _writeCount++; - var rawStage = stage & BufferStage.StageMask; + BufferStage rawStage = stage & BufferStage.StageMask; if (rawStage == BufferStage.Fragment) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs index 1801d87a6..83869ed02 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs @@ -401,7 +401,7 @@ namespace Ryujinx.Graphics.Gpu.Memory dstOffset += subRange.Size; } - foreach (var buffer in physicalBuffers) + foreach (Buffer buffer in physicalBuffers) { buffer.CopyToDependantVirtualBuffer(virtualBuffer); } @@ -983,7 +983,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// List used to track entries to delete private static void Prune(Dictionary dictionary, ref List toDelete) { - foreach (var entry in dictionary) + foreach (KeyValuePair entry in dictionary) { if (entry.Value.UnmappedSequence != entry.Value.Buffer.UnmappedSequence) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs index d51f96783..73647bef5 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs @@ -478,7 +478,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void CommitComputeBindings() { - var bufferCache = _channel.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _channel.MemoryManager.Physical.BufferCache; BindBuffers(bufferCache, _cpStorageBuffers, isStorage: true); BindBuffers(bufferCache, _cpUniformBuffers, isStorage: false); @@ -499,10 +499,10 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_bufferTextures.Count > 0) { - foreach (var binding in _bufferTextures) + foreach (BufferTextureBinding binding in _bufferTextures) { - var isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); - var range = bufferCache.GetBufferRange(binding.Range, BufferStageUtils.TextureBuffer(binding.Stage, binding.BindingInfo.Flags), isStore); + bool isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStageUtils.TextureBuffer(binding.Stage, binding.BindingInfo.Flags), isStore); binding.Texture.SetStorage(range); // The texture must be rebound to use the new storage if it was updated. @@ -524,19 +524,19 @@ namespace Ryujinx.Graphics.Gpu.Memory { ITexture[] textureArray = new ITexture[1]; - foreach (var binding in _bufferTextureArrays) + foreach (BufferTextureArrayBinding binding in _bufferTextureArrays) { - var range = bufferCache.GetBufferRange(binding.Range, BufferStage.None); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStage.None); binding.Texture.SetStorage(range); textureArray[0] = binding.Texture; binding.Array.SetTextures(binding.Index, textureArray); } - foreach (var binding in _bufferImageArrays) + foreach (BufferTextureArrayBinding binding in _bufferImageArrays) { - var isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); - var range = bufferCache.GetBufferRange(binding.Range, BufferStage.None, isStore); + bool isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStage.None, isStore); binding.Texture.SetStorage(range); textureArray[0] = binding.Texture; @@ -555,7 +555,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// True if the index buffer is in use public void CommitGraphicsBindings(bool indexed) { - var bufferCache = _channel.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _channel.MemoryManager.Physical.BufferCache; if (indexed) { @@ -750,19 +750,19 @@ namespace Ryujinx.Graphics.Gpu.Memory for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++) { - ref var buffers = ref bindings[(int)stage - 1]; + ref BuffersPerStage buffers = ref bindings[(int)stage - 1]; BufferStage bufferStage = BufferStageUtils.FromShaderStage(stage); for (int index = 0; index < buffers.Count; index++) { - ref var bindingInfo = ref buffers.Bindings[index]; + ref BufferDescriptor bindingInfo = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[bindingInfo.Slot]; if (!bounds.IsUnmapped) { - var isWrite = (bounds.Flags & BufferUsageFlags.Write) == BufferUsageFlags.Write; - var range = isStorage + bool isWrite = (bounds.Flags & BufferUsageFlags.Write) == BufferUsageFlags.Write; + BufferRange range = isStorage ? bufferCache.GetBufferRangeAligned(bounds.Range, bufferStage | BufferStageUtils.FromUsage(bounds.Flags), isWrite) : bufferCache.GetBufferRange(bounds.Range, bufferStage); @@ -792,14 +792,14 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int index = 0; index < buffers.Count; index++) { - ref var bindingInfo = ref buffers.Bindings[index]; + ref BufferDescriptor bindingInfo = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[bindingInfo.Slot]; if (!bounds.IsUnmapped) { - var isWrite = (bounds.Flags & BufferUsageFlags.Write) == BufferUsageFlags.Write; - var range = isStorage + bool isWrite = (bounds.Flags & BufferUsageFlags.Write) == BufferUsageFlags.Write; + BufferRange range = isStorage ? bufferCache.GetBufferRangeAligned(bounds.Range, BufferStageUtils.ComputeStorage(bounds.Flags), isWrite) : bufferCache.GetBufferRange(bounds.Range, BufferStage.Compute); @@ -840,11 +840,11 @@ namespace Ryujinx.Graphics.Gpu.Memory { for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++) { - ref var buffers = ref bindings[(int)stage - 1]; + ref BuffersPerStage buffers = ref bindings[(int)stage - 1]; for (int index = 0; index < buffers.Count; index++) { - ref var binding = ref buffers.Bindings[index]; + ref BufferDescriptor binding = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[binding.Slot]; diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs index cbbfa15b5..fab78971d 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Graphics.Gpu.Memory if (binding >= 0) { - var range = new BufferRange(_handle, 0, data.Length); + BufferRange range = new(_handle, 0, data.Length); _renderer.Pipeline.SetUniformBuffers([new BufferAssignment(0, range)]); } }; diff --git a/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs b/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs index bdb7cf2c2..77eb7c4a4 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { get { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { if (regionHandle.Dirty) { @@ -44,7 +44,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void Dispose() { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.Dispose(); } @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Action to call on read or write public void RegisterAction(RegionSignal action) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.RegisterAction(action); } @@ -70,7 +70,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Action to call on read or write public void RegisterPreciseAction(PreciseRegionSignal action) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.RegisterPreciseAction(action); } @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void Reprotect(bool asDirty = false) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.Reprotect(asDirty); } @@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void ForceDirty() { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.ForceDirty(); } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs index 33f9d591d..d60d59a36 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs @@ -464,7 +464,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int pages = (int)((endVaRounded - va) / PageSize); - var regions = new List(); + List regions = new(); for (int page = 0; page < pages - 1; page++) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs index 86de37876..7252b5404 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Gpu.Memory if (_dependencies != null) { - foreach (var dependency in _dependencies) + foreach (PhysicalDependency dependency in _dependencies) { if (dependency.PhysicalBuffer == buffer && dependency.VirtualOffset >= minimumVirtOffset) { @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_dependencies != null) { - foreach (var dependency in _dependencies) + foreach (PhysicalDependency dependency in _dependencies) { dependency.PhysicalBuffer.RemoveVirtualDependency(this); } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs index 21caf8287..8a78b99e0 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs @@ -101,10 +101,10 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { - var regions = _cpuMemory.GetHostRegions(singleRange.Address, singleRange.Size); + IEnumerable regions = _cpuMemory.GetHostRegions(singleRange.Address, singleRange.Size); if (regions != null && regions.Count() == 1) { @@ -138,7 +138,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { return _cpuMemory.GetSpan(singleRange.Address, (int)singleRange.Size, tracked); @@ -151,7 +151,7 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -198,7 +198,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int offset = 0; for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -321,7 +321,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { writeCallback(singleRange.Address, data); @@ -333,7 +333,7 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -381,12 +381,12 @@ namespace Ryujinx.Graphics.Gpu.Memory /// The memory tracking handle public GpuRegionHandle BeginTracking(MultiRange range, ResourceKind kind) { - var cpuRegionHandles = new RegionHandle[range.Count]; + RegionHandle[] cpuRegionHandles = new RegionHandle[range.Count]; int count = 0; for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); if (currentRange.Address != MemoryManager.PteUnmapped) { cpuRegionHandles[count++] = _cpuMemory.BeginTracking(currentRange.Address, currentRange.Size, (int)kind); diff --git a/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs index 71592e09a..6eae99afb 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Renderer that the support buffer will be used with public SupportBufferUpdater(IRenderer renderer) : base(renderer) { - var defaultScale = new Vector4 { X = 1f, Y = 0f, Z = 0f, W = 0f }; + Vector4 defaultScale = new() { X = 1f, Y = 0f, Z = 0f, W = 0f }; _data.RenderScale.AsSpan().Fill(defaultScale); DirtyRenderScale(0, SupportBuffer.RenderScaleMaxCount); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs index 805bce37a..4683a5d0c 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs @@ -59,7 +59,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { Target target = descriptor.Type != SamplerType.None ? ShaderTexture.GetTarget(descriptor.Type) : default; - var result = new TextureBindingInfo( + TextureBindingInfo result = new( target, descriptor.Set, descriptor.Binding, @@ -87,7 +87,7 @@ namespace Ryujinx.Graphics.Gpu.Shader Target target = ShaderTexture.GetTarget(descriptor.Type); FormatInfo formatInfo = ShaderTexture.GetFormatInfo(descriptor.Format); - var result = new TextureBindingInfo( + TextureBindingInfo result = new( target, formatInfo, descriptor.Set, diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs index 1ec47ca6e..5c8d5d5df 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Program to be added public void Add(CachedShaderProgram program) { - var specList = _cache.GetOrAdd(program.Shaders[0].Code, []); + ShaderSpecializationList specList = _cache.GetOrAdd(program.Shaders[0].Code, []); specList.Add(program); _shaderPrograms.Add(program); } @@ -51,7 +51,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { program = null; ShaderCodeAccessor codeAccessor = new(channel.MemoryManager, gpuVa); - bool hasSpecList = _cache.TryFindItem(codeAccessor, out var specList, out cachedGuestCode); + bool hasSpecList = _cache.TryFindItem(codeAccessor, out ShaderSpecializationList specList, out cachedGuestCode); return hasSpecList && specList.TryFindForCompute(channel, poolState, computeState, out program); } @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Programs added to the table public IEnumerable GetPrograms() { - foreach (var program in _shaderPrograms) + foreach (CachedShaderProgram program in _shaderPrograms) { yield return program; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs index 04c269f17..97749027b 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs @@ -180,8 +180,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// public void ClearCache() { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -258,8 +258,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Index of the shader on the cache public int AddShader(ReadOnlySpan data, ReadOnlySpan cb1Data) { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); TocHeader header = new(); @@ -267,9 +267,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache uint hash = CalcHash(data, cb1Data); - if (_toc.TryGetValue(hash, out var list)) + if (_toc.TryGetValue(hash, out List list)) { - foreach (var entry in list) + foreach (TocMemoryEntry entry in list) { if (data.Length != entry.CodeSize || cb1Data.Length != entry.Cb1DataSize) { @@ -427,7 +427,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Index of the data on the cache private void AddTocMemoryEntry(uint dataOffset, uint codeSize, uint cb1DataSize, uint hash, int index) { - if (!_toc.TryGetValue(hash, out var list)) + if (!_toc.TryGetValue(hash, out List list)) { _toc.Add(hash, list = []); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs index bfeb2107a..ab96b1168 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs @@ -301,11 +301,11 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache try { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: false); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: false); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: false); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: false); - using var guestTocFileStream = _guestStorage.OpenTocFileStream(); - using var guestDataFileStream = _guestStorage.OpenDataFileStream(); + using Stream guestTocFileStream = _guestStorage.OpenTocFileStream(); + using Stream guestDataFileStream = _guestStorage.OpenDataFileStream(); BinarySerializer tocReader = new(tocFileStream); BinarySerializer dataReader = new(dataFileStream); @@ -541,11 +541,11 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// A collection of disk cache output streams public DiskCacheOutputStreams GetOutputStreams(GpuContext context) { - var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); - var hostTocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - var hostDataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + FileStream hostTocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + FileStream hostDataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); return new DiskCacheOutputStreams(tocFileStream, dataFileStream, hostTocFileStream, hostDataFileStream); } @@ -563,7 +563,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < program.Shaders.Length; index++) { - var shader = program.Shaders[index]; + CachedShaderStage shader = program.Shaders[index]; if (shader == null || (shader.Info != null && shader.Info.Stage == ShaderStage.Compute)) { continue; @@ -572,8 +572,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache stagesBitMask |= 1u << index; } - var tocFileStream = streams != null ? streams.TocFileStream : DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - var dataFileStream = streams != null ? streams.DataFileStream : DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + FileStream tocFileStream = streams != null ? streams.TocFileStream : DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + FileStream dataFileStream = streams != null ? streams.DataFileStream : DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); ulong timestamp = (ulong)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds; @@ -604,7 +604,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < program.Shaders.Length; index++) { - var shader = program.Shaders[index]; + CachedShaderStage shader = program.Shaders[index]; if (shader == null) { continue; @@ -646,8 +646,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// GPU context public void ClearSharedCache() { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -659,8 +659,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// GPU context public void ClearHostCache(GpuContext context) { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -681,8 +681,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache DiskCacheOutputStreams streams, ulong timestamp) { - var tocFileStream = streams != null ? streams.HostTocFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - var dataFileStream = streams != null ? streams.HostDataFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + FileStream tocFileStream = streams != null ? streams.HostTocFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + FileStream dataFileStream = streams != null ? streams.HostDataFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); if (tocFileStream.Length == 0) { @@ -844,25 +844,25 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < info.CBuffers.Count; index++) { - var entry = info.CBuffers[index]; + BufferDescriptor entry = info.CBuffers[index]; dataWriter.WriteWithMagicAndSize(ref entry, BufdMagic); } for (int index = 0; index < info.SBuffers.Count; index++) { - var entry = info.SBuffers[index]; + BufferDescriptor entry = info.SBuffers[index]; dataWriter.WriteWithMagicAndSize(ref entry, BufdMagic); } for (int index = 0; index < info.Textures.Count; index++) { - var entry = info.Textures[index]; + TextureDescriptor entry = info.Textures[index]; dataWriter.WriteWithMagicAndSize(ref entry, TexdMagic); } for (int index = 0; index < info.Images.Count; index++) { - var entry = info.Images[index]; + TextureDescriptor entry = info.Images[index]; dataWriter.WriteWithMagicAndSize(ref entry, TexdMagic); } } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs index 044930203..a0d3e8c15 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs @@ -302,10 +302,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache Logger.Info?.Print(LogClass.Gpu, $"Rebuilding {_programList.Count} shaders..."); - using var streams = _hostStorage.GetOutputStreams(_context); + using DiskCacheOutputStreams streams = _hostStorage.GetOutputStreams(_context); int packagedShaders = 0; - foreach (var kv in _programList) + foreach (KeyValuePair kv in _programList) { if (!Active) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs index 1be75f242..393584bd4 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs @@ -4,6 +4,7 @@ using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; using System; using System.Runtime.InteropServices; +using TextureDescriptor = Ryujinx.Graphics.Gpu.Image.TextureDescriptor; namespace Ryujinx.Graphics.Gpu.Shader { @@ -177,7 +178,7 @@ namespace Ryujinx.Graphics.Gpu.Shader public TextureFormat QueryTextureFormat(int handle, int cbufSlot) { _state.SpecializationState?.RecordTextureFormat(_stageIndex, handle, cbufSlot); - var descriptor = GetTextureDescriptor(handle, cbufSlot); + TextureDescriptor descriptor = GetTextureDescriptor(handle, cbufSlot); return ConvertToTextureFormat(descriptor.UnpackFormat(), descriptor.UnpackSrgb()); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs index d5412c2a7..14f00beef 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs @@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Gpu.Shader GpuChannelComputeState computeState, ulong gpuVa) { - if (_cpPrograms.TryGetValue(gpuVa, out var cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa)) + if (_cpPrograms.TryGetValue(gpuVa, out CachedShaderProgram cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa)) { return cpShader; } @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Gpu.Shader { channel.TextureManager.UpdateRenderTargets(); - var rtControl = state.RtControl; - var msaaMode = state.RtMsaaMode; + RtControl rtControl = state.RtControl; + TextureMsaaMode msaaMode = state.RtMsaaMode; pipeline.SamplesCount = msaaMode.SamplesInX() * msaaMode.SamplesInY(); @@ -267,7 +267,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { int rtIndex = rtControl.UnpackPermutationIndex(index); - var colorState = rtColorStateSpan[rtIndex]; + RtColorState colorState = rtColorStateSpan[rtIndex]; if (index >= count || colorState.Format == 0 || colorState.WidthOrStride == 0) { @@ -312,12 +312,12 @@ namespace Ryujinx.Graphics.Gpu.Shader ref GpuChannelGraphicsState graphicsState, ShaderAddresses addresses) { - if (_gpPrograms.TryGetValue(addresses, out var gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses)) + if (_gpPrograms.TryGetValue(addresses, out CachedShaderProgram gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses)) { return gpShaders; } - if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out var cachedGuestCode)) + if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out CachedGraphicsGuestCode cachedGuestCode)) { _gpPrograms[addresses] = gpShaders; return gpShaders; @@ -590,7 +590,7 @@ namespace Ryujinx.Graphics.Gpu.Shader for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++) { - var tf = tfStateSpan[i]; + TfState tf = tfStateSpan[i]; descs[i] = new TransformFeedbackDescriptor( tf.BufferIndex, @@ -696,7 +696,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// The generated translator context public static TranslatorContext DecodeComputeShader(IGpuAccessor gpuAccessor, TargetApi api, ulong gpuVa) { - var options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute); + TranslationOptions options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute); return Translator.CreateContext(gpuVa, gpuAccessor, options); } @@ -713,7 +713,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// The generated translator context public static TranslatorContext DecodeGraphicsShader(IGpuAccessor gpuAccessor, TargetApi api, TranslationFlags flags, ulong gpuVa) { - var options = CreateTranslationOptions(api, flags); + TranslationOptions options = CreateTranslationOptions(api, flags); return Translator.CreateContext(gpuVa, gpuAccessor, options); } @@ -739,7 +739,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { ulong cb1DataAddress = channel.BufferManager.GetGraphicsUniformBufferAddress(0, 1); - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; codeA ??= memoryManager.GetSpan(vertexA.Address, vertexA.Size).ToArray(); codeB ??= memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray(); @@ -777,7 +777,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Compiled graphics shader code private static TranslatedShader TranslateShader(ShaderDumper dumper, GpuChannel channel, TranslatorContext context, byte[] code, bool asCompute) { - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; ulong cb1DataAddress = context.Stage == ShaderStage.Compute ? channel.BufferManager.GetComputeUniformBufferAddress(1) diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs index 3843f7581..0b981ff58 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { IdTable idTable = new(); - foreach (var shader in program.Shaders) + foreach (CachedShaderStage shader in program.Shaders) { if (shader == null) { @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Gpu.Shader out CachedShaderProgram program, out CachedGraphicsGuestCode guestCode) { - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; IdTable idTable = new(); guestCode = new CachedGraphicsGuestCode(); @@ -270,9 +270,9 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Programs added to the table public IEnumerable GetPrograms() { - foreach (var specList in _shaderPrograms.Values) + foreach (ShaderSpecializationList specList in _shaderPrograms.Values) { - foreach (var program in specList) + foreach (CachedShaderProgram program in specList) { yield return program; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs index ae8224455..c74c612a5 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs @@ -350,8 +350,8 @@ namespace Ryujinx.Graphics.Gpu.Shader { int totalSets = _resourceDescriptors.Length; - var descriptors = new ResourceDescriptorCollection[totalSets]; - var usages = new ResourceUsageCollection[totalSets]; + ResourceDescriptorCollection[] descriptors = new ResourceDescriptorCollection[totalSets]; + ResourceUsageCollection[] usages = new ResourceUsageCollection[totalSets]; for (int index = 0; index < totalSets; index++) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs index 1d2b873de..8549af715 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ref GpuChannelGraphicsState graphicsState, out CachedShaderProgram program) { - foreach (var entry in _entries) + foreach (CachedShaderProgram entry in _entries) { bool vertexAsCompute = entry.VertexAsCompute != null; bool usesDrawParameters = entry.Shaders[1]?.Info.UsesDrawParameters ?? false; @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// True if a compatible program is found, false otherwise public bool TryFindForCompute(GpuChannel channel, GpuChannelPoolState poolState, GpuChannelComputeState computeState, out CachedShaderProgram program) { - foreach (var entry in _entries) + foreach (CachedShaderProgram entry in _entries) { if (entry.SpecializationState.MatchesCompute(channel, ref poolState, computeState, true)) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs index 3ad4afb3d..709aa1ec1 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs @@ -6,10 +6,12 @@ using Ryujinx.Graphics.Gpu.Shader.DiskCache; using Ryujinx.Graphics.Shader; using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using TextureDescriptor = Ryujinx.Graphics.Shader.TextureDescriptor; namespace Ryujinx.Graphics.Gpu.Shader { @@ -214,23 +216,23 @@ namespace Ryujinx.Graphics.Gpu.Shader CachedShaderStage stage = stages[i]; if (stage?.Info != null) { - var textures = stage.Info.Textures; - var images = stage.Info.Images; + ReadOnlyCollection textures = stage.Info.Textures; + ReadOnlyCollection images = stage.Info.Images; - var texBindings = new Box[textures.Count]; - var imageBindings = new Box[images.Count]; + Box[] texBindings = new Box[textures.Count]; + Box[] imageBindings = new Box[images.Count]; int stageIndex = Math.Max(i - 1, 0); // Don't count VertexA for looking up spec state. No-Op for compute. for (int j = 0; j < textures.Count; j++) { - var texture = textures[j]; + TextureDescriptor texture = textures[j]; texBindings[j] = GetTextureSpecState(stageIndex, texture.HandleIndex, texture.CbufSlot); } for (int j = 0; j < images.Count; j++) { - var image = images[j]; + TextureDescriptor image = images[j]; imageBindings[j] = GetTextureSpecState(stageIndex, image.HandleIndex, image.CbufSlot); } @@ -758,7 +760,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ReadOnlySpan cachedTextureBuffer = Span.Empty; ReadOnlySpan cachedSamplerBuffer = Span.Empty; - foreach (var kv in _allTextures) + foreach (KeyValuePair> kv in _allTextures) { TextureKey textureKey = kv.Key; @@ -1021,10 +1023,10 @@ namespace Ryujinx.Graphics.Gpu.Shader ushort count = (ushort)_textureSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureSpecialization) + foreach (KeyValuePair> kv in _textureSpecialization) { - var textureKey = kv.Key; - var textureState = kv.Value; + TextureKey textureKey = kv.Key; + Box textureState = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.WriteWithMagicAndSize(ref textureState.Value, TexsMagic); @@ -1035,10 +1037,10 @@ namespace Ryujinx.Graphics.Gpu.Shader count = (ushort)_textureArrayFromBufferSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureArrayFromBufferSpecialization) + foreach (KeyValuePair kv in _textureArrayFromBufferSpecialization) { - var textureKey = kv.Key; - var length = kv.Value; + TextureKey textureKey = kv.Key; + int length = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.Write(ref length); @@ -1050,10 +1052,10 @@ namespace Ryujinx.Graphics.Gpu.Shader count = (ushort)_textureArrayFromPoolSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureArrayFromPoolSpecialization) + foreach (KeyValuePair kv in _textureArrayFromPoolSpecialization) { - var textureKey = kv.Key; - var length = kv.Value; + bool textureKey = kv.Key; + int length = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.Write(ref length); diff --git a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs index fe3dbfa73..eb6cbf426 100644 --- a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs @@ -87,7 +87,7 @@ namespace Ryujinx.Graphics.Gpu.Synchronization } using ManualResetEvent waitEvent = new(false); - var info = _syncpoints[id].RegisterCallback(threshold, (_) => waitEvent.Set()); + SyncpointWaiterHandle info = _syncpoints[id].RegisterCallback(threshold, (_) => waitEvent.Set()); if (info == null) { diff --git a/src/Ryujinx.Graphics.Gpu/Window.cs b/src/Ryujinx.Graphics.Gpu/Window.cs index 59cd4c8a6..5c3463f2a 100644 --- a/src/Ryujinx.Graphics.Gpu/Window.cs +++ b/src/Ryujinx.Graphics.Gpu/Window.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using Ryujinx.Memory.Range; using System; @@ -137,7 +138,7 @@ namespace Ryujinx.Graphics.Gpu Action releaseCallback, object userObj) { - if (!_context.PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!_context.PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { return false; } diff --git a/src/Ryujinx.Graphics.Host1x/Devices.cs b/src/Ryujinx.Graphics.Host1x/Devices.cs index 9de2b81a9..984a5abd6 100644 --- a/src/Ryujinx.Graphics.Host1x/Devices.cs +++ b/src/Ryujinx.Graphics.Host1x/Devices.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Host1x public void Dispose() { - foreach (var device in _devices.Values) + foreach (IDeviceState device in _devices.Values) { if (device is ThiDevice thi) { diff --git a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs index 2db74ce5e..bf9b14f89 100644 --- a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs +++ b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Host1x public void RegisterDevice(ClassId classId, IDeviceState device) { - var thi = new ThiDevice(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); + ThiDevice thi = new(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); _devices.RegisterDevice(classId, thi); } diff --git a/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs b/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs index c8871fe83..12eb788ac 100644 --- a/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs +++ b/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Graphics.Nvdec.FFmpeg.Native { handle = nint.Zero; - if (_librariesWhitelist.TryGetValue(libraryName, out var value)) + if (_librariesWhitelist.TryGetValue(libraryName, out (int, int) value)) { (int minVersion, int maxVersion) = value; diff --git a/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs b/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs index 043be1f2b..e9927c0f8 100644 --- a/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs +++ b/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs @@ -2,6 +2,7 @@ using Ryujinx.Common; using Ryujinx.Graphics.Device; using Ryujinx.Graphics.Texture; using Ryujinx.Graphics.Video; +using Ryujinx.Memory; using System; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; @@ -16,7 +17,7 @@ namespace Ryujinx.Graphics.Nvdec.Image { int lumaSize = GetBlockLinearSize(surface.Width, surface.Height, 1); - using var luma = mm.GetWritableRegion(ExtendOffset(lumaOffset), lumaSize); + using WritableRegion luma = mm.GetWritableRegion(ExtendOffset(lumaOffset), lumaSize); WriteLuma( luma.Memory.Span, @@ -27,7 +28,7 @@ namespace Ryujinx.Graphics.Nvdec.Image int chromaSize = GetBlockLinearSize(surface.UvWidth, surface.UvHeight, 2); - using var chroma = mm.GetWritableRegion(ExtendOffset(chromaOffset), chromaSize); + using WritableRegion chroma = mm.GetWritableRegion(ExtendOffset(chromaOffset), chromaSize); WriteChroma( chroma.Memory.Span, @@ -48,8 +49,8 @@ namespace Ryujinx.Graphics.Nvdec.Image { int lumaSize = GetBlockLinearSize(surface.Width, surface.Height / 2, 1); - using var lumaTop = mm.GetWritableRegion(ExtendOffset(lumaTopOffset), lumaSize); - using var lumaBottom = mm.GetWritableRegion(ExtendOffset(lumaBottomOffset), lumaSize); + using WritableRegion lumaTop = mm.GetWritableRegion(ExtendOffset(lumaTopOffset), lumaSize); + using WritableRegion lumaBottom = mm.GetWritableRegion(ExtendOffset(lumaBottomOffset), lumaSize); WriteLuma( lumaTop.Memory.Span, @@ -67,8 +68,8 @@ namespace Ryujinx.Graphics.Nvdec.Image int chromaSize = GetBlockLinearSize(surface.UvWidth, surface.UvHeight / 2, 2); - using var chromaTop = mm.GetWritableRegion(ExtendOffset(chromaTopOffset), chromaSize); - using var chromaBottom = mm.GetWritableRegion(ExtendOffset(chromaBottomOffset), chromaSize); + using WritableRegion chromaTop = mm.GetWritableRegion(ExtendOffset(chromaTopOffset), chromaSize); + using WritableRegion chromaBottom = mm.GetWritableRegion(ExtendOffset(chromaBottomOffset), chromaSize); WriteChroma( chromaTop.Memory.Span, diff --git a/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs b/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs index 29e260d63..7a8fbf9b6 100644 --- a/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs +++ b/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs @@ -36,7 +36,7 @@ namespace Ryujinx.Graphics.Nvdec public void DestroyContext(long id) { - if (_contexts.TryRemove(id, out var context)) + if (_contexts.TryRemove(id, out NvdecDecoderContext context)) { context.Dispose(); } @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Nvdec public void BindContext(long id) { - if (_contexts.TryGetValue(id, out var context)) + if (_contexts.TryGetValue(id, out NvdecDecoderContext context)) { _currentContext = context; } diff --git a/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs b/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs index 5ed508647..6c294adf6 100644 --- a/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs +++ b/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs @@ -4,6 +4,7 @@ using Ryujinx.Graphics.Nvdec.Image; using Ryujinx.Graphics.Nvdec.Types.Vp9; using Ryujinx.Graphics.Nvdec.Vp9; using Ryujinx.Graphics.Video; +using Ryujinx.Memory; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -50,7 +51,7 @@ namespace Ryujinx.Graphics.Nvdec int miCols = BitUtils.DivRoundUp(pictureInfo.CurrentFrameSize.Width, 8); int miRows = BitUtils.DivRoundUp(pictureInfo.CurrentFrameSize.Height, 8); - using var mvsRegion = rm.MemoryManager.GetWritableRegion(ExtendOffset(state.Vp9SetColMvWriteBufOffset), miRows * miCols * 16); + using WritableRegion mvsRegion = rm.MemoryManager.GetWritableRegion(ExtendOffset(state.Vp9SetColMvWriteBufOffset), miRows * miCols * 16); Span mvsOut = MemoryMarshal.Cast(mvsRegion.Memory.Span); @@ -80,9 +81,9 @@ namespace Ryujinx.Graphics.Nvdec private static void WriteBackwardUpdates(DeviceMemoryManager mm, uint offset, ref Vp9BackwardUpdates counts) { - using var backwardUpdatesRegion = mm.GetWritableRegion(ExtendOffset(offset), Unsafe.SizeOf()); + using WritableRegion backwardUpdatesRegion = mm.GetWritableRegion(ExtendOffset(offset), Unsafe.SizeOf()); - ref var backwardUpdates = ref MemoryMarshal.Cast(backwardUpdatesRegion.Memory.Span)[0]; + ref BackwardUpdates backwardUpdates = ref MemoryMarshal.Cast(backwardUpdatesRegion.Memory.Span)[0]; backwardUpdates = new BackwardUpdates(ref counts); } diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs b/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs index f615f1522..621af0e5d 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs @@ -40,7 +40,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects private void Initialize() { - var scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/area_scaling.glsl"); + string scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/area_scaling.glsl"); _scalingShaderProgram = CompileProgram(scalingShader, ShaderType.ComputeShader); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs b/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs index 514e8c8c2..96005c8ad 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs @@ -57,10 +57,10 @@ namespace Ryujinx.Graphics.OpenGL.Effects private void Initialize() { - var scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_scaling.glsl"); - var sharpeningShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_sharpening.glsl"); - var fsrA = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_a.h"); - var fsr1 = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_fsr1.h"); + string scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_scaling.glsl"); + string sharpeningShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_sharpening.glsl"); + string fsrA = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_a.h"); + string fsr1 = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_fsr1.h"); scalingShader = scalingShader.Replace("#include \"ffx_a.h\"", fsrA); scalingShader = scalingShader.Replace("#include \"ffx_fsr1.h\"", fsr1); @@ -97,8 +97,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects if (_intermediaryTexture == null || _intermediaryTexture.Info.Width != width || _intermediaryTexture.Info.Height != height) { _intermediaryTexture?.Dispose(); - var originalInfo = view.Info; - var info = new TextureCreateInfo(width, + TextureCreateInfo originalInfo = view.Info; + TextureCreateInfo info = new(width, height, originalInfo.Depth, originalInfo.Levels, @@ -118,7 +118,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects _intermediaryTexture.CreateDefaultView(); } - var textureView = _intermediaryTexture.CreateView(_intermediaryTexture.Info, 0, 0) as TextureView; + TextureView textureView = _intermediaryTexture.CreateView(_intermediaryTexture.Info, 0, 0) as TextureView; int previousProgram = GL.GetInteger(GetPName.CurrentProgram); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs index 1aaaac2ff..99b034be4 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects _textureStorage.CreateDefaultView(); } - var textureView = _textureStorage.CreateView(view.Info, 0, 0) as TextureView; + TextureView textureView = _textureStorage.CreateView(view.Info, 0, 0) as TextureView; int previousProgram = GL.GetInteger(GetPName.CurrentProgram); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); @@ -62,8 +62,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects GL.BindImageTexture(0, textureView.Handle, 0, false, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8); GL.UseProgram(_shaderProgram); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); view.Bind(0); GL.Uniform1(_inputUniform, 0); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs b/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs index 2bb67dde8..ad0ccd23b 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects public static int CompileProgram(string[] shaders, ShaderType shaderType) { - var shader = GL.CreateShader(shaderType); + int shader = GL.CreateShader(shaderType); GL.ShaderSource(shader, shaders.Length, shaders, (int[])null); GL.CompileShader(shader); @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects return 0; } - var program = GL.CreateProgram(); + int program = GL.CreateProgram(); GL.AttachShader(program, shader); GL.LinkProgram(program); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs index 13f8dc52a..645d07fa3 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs @@ -1,5 +1,6 @@ using OpenTK.Graphics.OpenGL; using Ryujinx.Common; +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.OpenGL.Image; using System; @@ -78,7 +79,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa private unsafe void RecreateShaders(int width, int height) { string baseShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa.hlsl"); - var pixelSizeDefine = $"#define SMAA_RT_METRICS float4(1.0 / {width}.0, 1.0 / {height}.0, {width}, {height}) \n"; + string pixelSizeDefine = $"#define SMAA_RT_METRICS float4(1.0 / {width}.0, 1.0 / {height}.0, {width}, {height}) \n"; _edgeShaderPrograms = new int[_qualities.Length]; _blendShaderPrograms = new int[_qualities.Length]; @@ -86,20 +87,20 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa for (int i = 0; i < +_edgeShaderPrograms.Length; i++) { - var presets = $"#version 430 core \n#define {_qualities[i]} 1 \n{pixelSizeDefine}#define SMAA_GLSL_4 1 \nlayout (local_size_x = 16, local_size_y = 16) in;\n{baseShader}"; + string presets = $"#version 430 core \n#define {_qualities[i]} 1 \n{pixelSizeDefine}#define SMAA_GLSL_4 1 \nlayout (local_size_x = 16, local_size_y = 16) in;\n{baseShader}"; - var edgeShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_edge.glsl"); - var blendShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_blend.glsl"); - var neighbourShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_neighbour.glsl"); + string edgeShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_edge.glsl"); + string blendShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_blend.glsl"); + string neighbourShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_neighbour.glsl"); - var shaders = new string[] { presets, edgeShaderData }; - var edgeProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + string[] shaders = new string[] { presets, edgeShaderData }; + int edgeProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); shaders[1] = blendShaderData; - var blendProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + int blendProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); shaders[1] = neighbourShaderData; - var neighbourProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + int neighbourProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); _edgeShaderPrograms[i] = edgeProgram; _blendShaderPrograms[i] = blendProgram; @@ -116,7 +117,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa private void Initialize() { - var areaInfo = new TextureCreateInfo(AreaWidth, + TextureCreateInfo areaInfo = new(AreaWidth, AreaHeight, 1, 1, @@ -132,7 +133,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa SwizzleComponent.Blue, SwizzleComponent.Alpha); - var searchInfo = new TextureCreateInfo(SearchWidth, + TextureCreateInfo searchInfo = new(SearchWidth, SearchHeight, 1, 1, @@ -151,11 +152,11 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa _areaTexture = new TextureStorage(_renderer, areaInfo); _searchTexture = new TextureStorage(_renderer, searchInfo); - var areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaAreaTexture.bin"); - var searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaSearchTexture.bin"); + MemoryOwner areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaAreaTexture.bin"); + MemoryOwner searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaSearchTexture.bin"); - var areaView = _areaTexture.CreateDefaultView(); - var searchView = _searchTexture.CreateDefaultView(); + ITexture areaView = _areaTexture.CreateDefaultView(); + ITexture searchView = _searchTexture.CreateDefaultView(); areaView.SetData(areaTexture); searchView.SetData(searchTexture); @@ -178,13 +179,13 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa RecreateShaders(view.Width, view.Height); } - var textureView = _outputTexture.CreateView(view.Info, 0, 0) as TextureView; - var edgeOutput = _edgeOutputTexture.DefaultView as TextureView; - var blendOutput = _blendOutputTexture.DefaultView as TextureView; - var areaTexture = _areaTexture.DefaultView as TextureView; - var searchTexture = _searchTexture.DefaultView as TextureView; + TextureView textureView = _outputTexture.CreateView(view.Info, 0, 0) as TextureView; + TextureView edgeOutput = _edgeOutputTexture.DefaultView as TextureView; + TextureView blendOutput = _blendOutputTexture.DefaultView as TextureView; + TextureView areaTexture = _areaTexture.DefaultView as TextureView; + TextureView searchTexture = _searchTexture.DefaultView as TextureView; - var previousFramebuffer = GL.GetInteger(GetPName.FramebufferBinding); + int previousFramebuffer = GL.GetInteger(GetPName.FramebufferBinding); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); GL.ActiveTexture(TextureUnit.Texture0); int previousTextureBinding0 = GL.GetInteger(GetPName.TextureBinding2D); @@ -193,7 +194,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa GL.ActiveTexture(TextureUnit.Texture2); int previousTextureBinding2 = GL.GetInteger(GetPName.TextureBinding2D); - var framebuffer = new Framebuffer(); + Framebuffer framebuffer = new(); framebuffer.Bind(); framebuffer.AttachColor(0, edgeOutput); GL.Clear(ClearBufferMask.ColorBufferBit); @@ -206,8 +207,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa framebuffer.Dispose(); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); int previousProgram = GL.GetInteger(GetPName.CurrentProgram); GL.BindImageTexture(0, edgeOutput!.Handle, 0, false, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs b/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs index 490c0c585..64e4fe36d 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.OpenGL.Image if (Avx2.IsSupported) { - var mask = Vector256.Create( + Vector256 mask = Vector256.Create( (byte)3, (byte)0, (byte)1, (byte)2, (byte)7, (byte)4, (byte)5, (byte)6, (byte)11, (byte)8, (byte)9, (byte)10, @@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 32) { - var dataVec = Avx.LoadVector256(pInput + i); + Vector256 dataVec = Avx.LoadVector256(pInput + i); dataVec = Avx2.Shuffle(dataVec, mask); @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.OpenGL.Image } else if (Ssse3.IsSupported) { - var mask = Vector128.Create( + Vector128 mask = Vector128.Create( (byte)3, (byte)0, (byte)1, (byte)2, (byte)7, (byte)4, (byte)5, (byte)6, (byte)11, (byte)8, (byte)9, (byte)10, @@ -59,7 +59,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 16) { - var dataVec = Sse2.LoadVector128(pInput + i); + Vector128 dataVec = Sse2.LoadVector128(pInput + i); dataVec = Ssse3.Shuffle(dataVec, mask); @@ -70,8 +70,8 @@ namespace Ryujinx.Graphics.OpenGL.Image start = sizeAligned; } - var outSpan = MemoryMarshal.Cast(output); - var dataSpan = MemoryMarshal.Cast(data); + Span outSpan = MemoryMarshal.Cast(output); + ReadOnlySpan dataSpan = MemoryMarshal.Cast(data); for (int i = start / sizeof(uint); i < dataSpan.Length; i++) { outSpan[i] = BitOperations.RotateLeft(dataSpan[i], 8); @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.OpenGL.Image if (Avx2.IsSupported) { - var mask = Vector256.Create( + Vector256 mask = Vector256.Create( (byte)1, (byte)2, (byte)3, (byte)0, (byte)5, (byte)6, (byte)7, (byte)4, (byte)9, (byte)10, (byte)11, (byte)8, @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 32) { - var dataVec = Avx.LoadVector256(pInput + i); + Vector256 dataVec = Avx.LoadVector256(pInput + i); dataVec = Avx2.Shuffle(dataVec, mask); @@ -116,7 +116,7 @@ namespace Ryujinx.Graphics.OpenGL.Image } else if (Ssse3.IsSupported) { - var mask = Vector128.Create( + Vector128 mask = Vector128.Create( (byte)1, (byte)2, (byte)3, (byte)0, (byte)5, (byte)6, (byte)7, (byte)4, (byte)9, (byte)10, (byte)11, (byte)8, @@ -128,7 +128,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 16) { - var dataVec = Sse2.LoadVector128(pInput + i); + Vector128 dataVec = Sse2.LoadVector128(pInput + i); dataVec = Ssse3.Shuffle(dataVec, mask); @@ -139,8 +139,8 @@ namespace Ryujinx.Graphics.OpenGL.Image start = sizeAligned; } - var outSpan = MemoryMarshal.Cast(output); - var dataSpan = MemoryMarshal.Cast(data); + Span outSpan = MemoryMarshal.Cast(output); + ReadOnlySpan dataSpan = MemoryMarshal.Cast(data); for (int i = start / sizeof(uint); i < dataSpan.Length; i++) { outSpan[i] = BitOperations.RotateRight(dataSpan[i], 8); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs index 8e728a2bb..231d9c97b 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.OpenGL.Image /// public void SetData(MemoryOwner data) { - var dataSpan = data.Span; + Span dataSpan = data.Span; Buffer.SetData(_buffer, _bufferOffset, dataSpan[..Math.Min(dataSpan.Length, _bufferSize)]); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs index d21b5f040..648ba1bc2 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs @@ -91,8 +91,8 @@ void main() int srcComponentsCount = srcBpp / componentSize; int dstComponentsCount = dstBpp / componentSize; - var srcFormat = GetFormat(componentSize, srcComponentsCount); - var dstFormat = GetFormat(componentSize, dstComponentsCount); + SizedInternalFormat srcFormat = GetFormat(componentSize, srcComponentsCount); + SizedInternalFormat dstFormat = GetFormat(componentSize, dstComponentsCount); GL.UseProgram(srcBpp < dstBpp ? GetWideningShader(componentSize, srcComponentsCount, dstComponentsCount) diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs index 7e43d2741..b045870a7 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs @@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { unsafe { - var dataSpan = data.Span; + Span dataSpan = data.Span; fixed (byte* ptr = dataSpan) { ReadFrom((nint)ptr, dataSpan.Length); diff --git a/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs b/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs index 331776122..05e1eee49 100644 --- a/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs +++ b/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs @@ -6,6 +6,7 @@ using Ryujinx.Graphics.OpenGL.Image; using Ryujinx.Graphics.OpenGL.Queries; using Ryujinx.Graphics.Shader.Translation; using System; +using BufferAccess = Ryujinx.Graphics.GAL.BufferAccess; namespace Ryujinx.Graphics.OpenGL { @@ -63,7 +64,7 @@ namespace Ryujinx.Graphics.OpenGL { BufferCount++; - var memType = access & GAL.BufferAccess.MemoryTypeMask; + BufferAccess memType = access & GAL.BufferAccess.MemoryTypeMask; if (memType == GAL.BufferAccess.HostMemory) { diff --git a/src/Ryujinx.Graphics.OpenGL/Pipeline.cs b/src/Ryujinx.Graphics.OpenGL/Pipeline.cs index 813c43f33..6774f0fba 100644 --- a/src/Ryujinx.Graphics.OpenGL/Pipeline.cs +++ b/src/Ryujinx.Graphics.OpenGL/Pipeline.cs @@ -1205,7 +1205,7 @@ namespace Ryujinx.Graphics.OpenGL { int vIndex = index * 4; - var region = regions[index]; + Rectangle region = regions[index]; bool enabled = (region.X | region.Y) != 0 || region.Width != 0xffff || region.Height != 0xffff; uint mask = 1u << index; diff --git a/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs b/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs index 1530c9d26..436f03756 100644 --- a/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs +++ b/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs @@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.OpenGL.Queries public void Update() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Flush(false); } @@ -48,7 +48,7 @@ namespace Ryujinx.Graphics.OpenGL.Queries public void Dispose() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Dispose(); } diff --git a/src/Ryujinx.Graphics.OpenGL/VertexArray.cs b/src/Ryujinx.Graphics.OpenGL/VertexArray.cs index ec151be75..43f2bef16 100644 --- a/src/Ryujinx.Graphics.OpenGL/VertexArray.cs +++ b/src/Ryujinx.Graphics.OpenGL/VertexArray.cs @@ -176,7 +176,7 @@ namespace Ryujinx.Graphics.OpenGL { int vbIndex = BitOperations.TrailingZeroCount(buffersInUse); - ref var vb = ref _vertexBuffers[vbIndex]; + ref VertexBufferDescriptor vb = ref _vertexBuffers[vbIndex]; int requiredSize = vertexCount * vb.Stride; @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.OpenGL { int vbIndex = BitOperations.TrailingZeroCount(buffersLimited); - ref var vb = ref _vertexBuffers[vbIndex]; + ref VertexBufferDescriptor vb = ref _vertexBuffers[vbIndex]; GL.BindVertexBuffer(vbIndex, vb.Buffer.Handle.ToInt32(), (nint)vb.Buffer.Offset, vb.Stride); diff --git a/src/Ryujinx.Graphics.OpenGL/Window.cs b/src/Ryujinx.Graphics.OpenGL/Window.cs index 1dc8a51f6..e193ccf0c 100644 --- a/src/Ryujinx.Graphics.OpenGL/Window.cs +++ b/src/Ryujinx.Graphics.OpenGL/Window.cs @@ -75,13 +75,13 @@ namespace Ryujinx.Graphics.OpenGL if (_antiAliasing != null) { - var oldView = viewConverted; + TextureView oldView = viewConverted; viewConverted = _antiAliasing.Run(viewConverted, _width, _height); if (viewConverted.Format.IsBgr()) { - var swappedView = _renderer.TextureCopy.BgraSwap(viewConverted); + TextureView swappedView = _renderer.TextureCopy.BgraSwap(viewConverted); viewConverted?.Dispose(); @@ -329,7 +329,7 @@ namespace Ryujinx.Graphics.OpenGL case AntiAliasing.SmaaMedium: case AntiAliasing.SmaaHigh: case AntiAliasing.SmaaUltra: - var quality = _currentAntiAliasing - AntiAliasing.SmaaLow; + int quality = _currentAntiAliasing - AntiAliasing.SmaaLow; if (_antiAliasing is SmaaPostProcessingEffect smaa) { smaa.Quality = quality; @@ -393,7 +393,7 @@ namespace Ryujinx.Graphics.OpenGL { _upscaledTexture?.Dispose(); - var info = new TextureCreateInfo( + TextureCreateInfo info = new( _width, _height, 1, diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs index 16c9826f3..77adffb09 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl if (context.Definitions.TransformFeedbackEnabled && context.Definitions.LastInVertexPipeline) { - var tfOutput = context.Definitions.GetTransformFeedbackOutput(AttributeConsts.PositionX); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(AttributeConsts.PositionX); if (tfOutput.Valid) { context.AppendLine($"layout (xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}) out gl_PerVertex"); @@ -338,7 +338,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareSamplers(CodeGenContext context, IEnumerable definitions) { - foreach (var definition in definitions) + foreach (TextureDefinition definition in definitions) { string arrayDecl = string.Empty; @@ -366,7 +366,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareImages(CodeGenContext context, IEnumerable definitions) { - foreach (var definition in definitions) + foreach (TextureDefinition definition in definitions) { string arrayDecl = string.Empty; @@ -413,7 +413,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl } else { - foreach (var ioDefinition in inputs.OrderBy(x => x.Location)) + foreach (IoDefinition ioDefinition in inputs.OrderBy(x => x.Location)) { DeclareInputAttribute(context, ioDefinition.Location, ioDefinition.Component); } @@ -427,7 +427,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareInputAttributesPerPatch(CodeGenContext context, IEnumerable inputs) { - foreach (var ioDefinition in inputs.OrderBy(x => x.Location)) + foreach (IoDefinition ioDefinition in inputs.OrderBy(x => x.Location)) { DeclareInputAttributePerPatch(context, ioDefinition.Location); } @@ -517,7 +517,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl outputs = outputs.Skip(2); } - foreach (var ioDefinition in outputs) + foreach (IoDefinition ioDefinition in outputs) { DeclareOutputAttribute(context, ioDefinition.Location, ioDefinition.Component); } @@ -544,7 +544,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl string xfb = string.Empty; - var tfOutput = context.Definitions.GetTransformFeedbackOutput(location, component); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(location, component); if (tfOutput.Valid) { xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}"; @@ -566,7 +566,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl string xfb = string.Empty; - var tfOutput = context.Definitions.GetTransformFeedbackOutput(location, 0); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(location, 0); if (tfOutput.Valid) { xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}"; @@ -602,7 +602,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareOutputAttributesPerPatch(CodeGenContext context, IEnumerable outputs) { - foreach (var ioDefinition in outputs) + foreach (IoDefinition ioDefinition in outputs) { DeclareOutputAttributePerPatch(context, ioDefinition.Location); } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs index d5448856d..9d4ea5348 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions Debug.Assert(funcId.Type == OperandType.Constant); - var function = context.GetFunction(funcId.Value); + StructuredFunction function = context.GetFunction(funcId.Value); string[] args = new string[operation.SourcesCount - 1]; diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs index 4308b08f8..bd58b0dfd 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions bool isArray = (texOp.Type & SamplerType.Array) != 0; - var texCallBuilder = new StringBuilder(); + StringBuilder texCallBuilder = new(); if (texOp.Inst == Instruction.ImageAtomic) { diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs index 0e415ab46..e317580a2 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs @@ -129,7 +129,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private BlockState GetBlockStateLazy(AstBlock block) { - if (!_labels.TryGetValue(block, out var blockState)) + if (!_labels.TryGetValue(block, out BlockState blockState)) { blockState = new BlockState(); @@ -141,7 +141,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction NewBlock() { - var label = Label(); + Instruction label = Label(); Branch(label); AddLabel(label); return label; @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction[] GetMainInterface() { - var mainInterface = new List(); + List mainInterface = new(); mainInterface.AddRange(Inputs.Values); mainInterface.AddRange(Outputs.Values); @@ -198,7 +198,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstOperation operation) { - var opResult = Instructions.Generate(this, operation); + OperationResult opResult = Instructions.Generate(this, operation); return BitcastIfNeeded(type, opResult.Type, opResult.Value); } else if (node is AstOperand operand) @@ -220,7 +220,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstOperation operation) { - var opResult = Instructions.Generate(this, operation); + OperationResult opResult = Instructions.Generate(this, operation); type = opResult.Type; return opResult.Value; } @@ -275,13 +275,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction GetLocal(AggregateType dstType, AstOperand local) { - var srcType = local.VarType; + AggregateType srcType = local.VarType; return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetLocalPointer(local))); } public Instruction GetArgument(AggregateType dstType, AstOperand funcArg) { - var srcType = funcArg.VarType; + AggregateType srcType = funcArg.VarType; return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetArgumentPointer(funcArg))); } @@ -341,8 +341,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (srcType == AggregateType.Bool) { - var intTrue = Constant(TypeS32(), IrConsts.True); - var intFalse = Constant(TypeS32(), IrConsts.False); + Instruction intTrue = Constant(TypeS32(), IrConsts.True); + Instruction intFalse = Constant(TypeS32(), IrConsts.False); return BitcastIfNeeded(dstType, AggregateType.S32, Select(TypeS32(), value, intTrue, intFalse)); } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs index 19041981a..c0a597a10 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs @@ -20,10 +20,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareParameters(CodeGenContext context, IEnumerable argTypes, int argIndex) { - foreach (var argType in argTypes) + foreach (AggregateType argType in argTypes) { - var argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType)); - var spvArg = context.FunctionParameter(argPointerType); + SpvInstruction argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType)); + SpvInstruction spvArg = context.FunctionParameter(argPointerType); context.DeclareArgument(argIndex++, spvArg); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { foreach (AstOperand local in function.Locals) { - var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType)); - var spvLocal = context.Variable(localPointerType, StorageClass.Function); + SpvInstruction localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType)); + SpvInstruction spvLocal = context.Variable(localPointerType, StorageClass.Function); context.AddLocalVariable(spvLocal); context.DeclareLocal(local, spvLocal); @@ -60,8 +60,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { foreach ((int id, MemoryDefinition memory) in memories) { - var pointerType = context.TypePointer(storage, context.GetType(memory.Type, memory.ArrayLength)); - var variable = context.Variable(pointerType, storage); + SpvInstruction pointerType = context.TypePointer(storage, context.GetType(memory.Type, memory.ArrayLength)); + SpvInstruction variable = context.Variable(pointerType, storage); context.AddGlobalVariable(variable); @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var structType = context.TypeStruct(false, structFieldTypes); + SpvInstruction structType = context.TypeStruct(false, structFieldTypes); if (decoratedTypes.Add(structType)) { @@ -135,8 +135,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var pointerType = context.TypePointer(StorageClass.Uniform, structType); - var variable = context.Variable(pointerType, StorageClass.Uniform); + SpvInstruction pointerType = context.TypePointer(StorageClass.Uniform, structType); + SpvInstruction variable = context.Variable(pointerType, StorageClass.Uniform); context.Name(variable, buffer.Name); context.Decorate(variable, Decoration.DescriptorSet, (LiteralInteger)setIndex); @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareSamplers(CodeGenContext context, IEnumerable samplers) { - foreach (var sampler in samplers) + foreach (TextureDefinition sampler in samplers) { int setIndex = context.TargetApi == TargetApi.Vulkan ? sampler.Set : 0; @@ -165,7 +165,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv if (sampler.Type != SamplerType.None) { - var dim = (sampler.Type & SamplerType.Mask) switch + Dim dim = (sampler.Type & SamplerType.Mask) switch { SamplerType.Texture1D => Dim.Dim1D, SamplerType.Texture2D => Dim.Dim2D, @@ -191,22 +191,22 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv imageType = sampledImageType = context.TypeSampler(); } - var sampledOrSeparateImageType = sampler.Separate ? imageType : sampledImageType; - var sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledOrSeparateImageType); - var sampledImageArrayPointerType = sampledImagePointerType; + SpvInstruction sampledOrSeparateImageType = sampler.Separate ? imageType : sampledImageType; + SpvInstruction sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledOrSeparateImageType); + SpvInstruction sampledImageArrayPointerType = sampledImagePointerType; if (sampler.ArrayLength == 0) { - var sampledImageArrayType = context.TypeRuntimeArray(sampledOrSeparateImageType); + SpvInstruction sampledImageArrayType = context.TypeRuntimeArray(sampledOrSeparateImageType); sampledImageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageArrayType); } else if (sampler.ArrayLength != 1) { - var sampledImageArrayType = context.TypeArray(sampledOrSeparateImageType, context.Constant(context.TypeU32(), sampler.ArrayLength)); + SpvInstruction sampledImageArrayType = context.TypeArray(sampledOrSeparateImageType, context.Constant(context.TypeU32(), sampler.ArrayLength)); sampledImageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageArrayType); } - var sampledImageVariable = context.Variable(sampledImageArrayPointerType, StorageClass.UniformConstant); + SpvInstruction sampledImageVariable = context.Variable(sampledImageArrayPointerType, StorageClass.UniformConstant); context.Samplers.Add(new(sampler.Set, sampler.Binding), new SamplerDeclaration( imageType, @@ -225,13 +225,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareImages(CodeGenContext context, IEnumerable images) { - foreach (var image in images) + foreach (TextureDefinition image in images) { int setIndex = context.TargetApi == TargetApi.Vulkan ? image.Set : 0; - var dim = GetDim(image.Type); + Dim dim = GetDim(image.Type); - var imageType = context.TypeImage( + SpvInstruction imageType = context.TypeImage( context.GetType(image.Format.GetComponentType()), dim, image.Type.HasFlag(SamplerType.Shadow), @@ -240,21 +240,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AccessQualifier.ReadWrite, GetImageFormat(image.Format)); - var imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType); - var imageArrayPointerType = imagePointerType; + SpvInstruction imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType); + SpvInstruction imageArrayPointerType = imagePointerType; if (image.ArrayLength == 0) { - var imageArrayType = context.TypeRuntimeArray(imageType); + SpvInstruction imageArrayType = context.TypeRuntimeArray(imageType); imageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, imageArrayType); } else if (image.ArrayLength != 1) { - var imageArrayType = context.TypeArray(imageType, context.Constant(context.TypeU32(), image.ArrayLength)); + SpvInstruction imageArrayType = context.TypeArray(imageType, context.Constant(context.TypeU32(), image.ArrayLength)); imageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, imageArrayType); } - var imageVariable = context.Variable(imageArrayPointerType, StorageClass.UniformConstant); + SpvInstruction imageVariable = context.Variable(imageArrayPointerType, StorageClass.UniformConstant); context.Images.Add(new(image.Set, image.Binding), new ImageDeclaration(imageType, imagePointerType, imageVariable, image.ArrayLength != 1)); @@ -338,7 +338,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv if (context.Definitions.Stage == ShaderStage.Fragment && context.Definitions.DualSourceBlend) { - foreach (var ioDefinition in info.IoDefinitions) + foreach (IoDefinition ioDefinition in info.IoDefinitions) { if (ioDefinition.IoVariable == IoVariable.FragmentOutputColor && ioDefinition.Location < firstLocation) { @@ -347,13 +347,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - foreach (var ioDefinition in info.IoDefinitions) + foreach (IoDefinition ioDefinition in info.IoDefinitions) { PixelImap iq = PixelImap.Unused; if (context.Definitions.Stage == ShaderStage.Fragment) { - var ioVariable = ioDefinition.IoVariable; + IoVariable ioVariable = ioDefinition.IoVariable; if (ioVariable == IoVariable.UserDefined) { iq = context.Definitions.ImapTypes[ioDefinition.Location].GetFirstUsedType(); @@ -389,11 +389,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (context.Definitions.Stage != ShaderStage.Vertex) { - var perVertexInputStructType = CreatePerVertexStructType(context); + SpvInstruction perVertexInputStructType = CreatePerVertexStructType(context); int arraySize = context.Definitions.Stage == ShaderStage.Geometry ? context.Definitions.InputTopology.ToInputVertices() : 32; - var perVertexInputArrayType = context.TypeArray(perVertexInputStructType, context.Constant(context.TypeU32(), arraySize)); - var perVertexInputPointerType = context.TypePointer(StorageClass.Input, perVertexInputArrayType); - var perVertexInputVariable = context.Variable(perVertexInputPointerType, StorageClass.Input); + SpvInstruction perVertexInputArrayType = context.TypeArray(perVertexInputStructType, context.Constant(context.TypeU32(), arraySize)); + SpvInstruction perVertexInputPointerType = context.TypePointer(StorageClass.Input, perVertexInputArrayType); + SpvInstruction perVertexInputVariable = context.Variable(perVertexInputPointerType, StorageClass.Input); context.Name(perVertexInputVariable, "gl_in"); @@ -411,11 +411,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var perVertexOutputStructType = CreatePerVertexStructType(context); + SpvInstruction perVertexOutputStructType = CreatePerVertexStructType(context); void DecorateTfo(IoVariable ioVariable, int fieldIndex) { - if (context.Definitions.TryGetTransformFeedbackOutput(ioVariable, 0, 0, out var transformFeedbackOutput)) + if (context.Definitions.TryGetTransformFeedbackOutput(ioVariable, 0, 0, out TransformFeedbackOutput transformFeedbackOutput)) { context.MemberDecorate(perVertexOutputStructType, fieldIndex, Decoration.XfbBuffer, (LiteralInteger)transformFeedbackOutput.Buffer); context.MemberDecorate(perVertexOutputStructType, fieldIndex, Decoration.XfbStride, (LiteralInteger)transformFeedbackOutput.Stride); @@ -439,8 +439,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv perVertexOutputArrayType = perVertexOutputStructType; } - var perVertexOutputPointerType = context.TypePointer(StorageClass.Output, perVertexOutputArrayType); - var perVertexOutputVariable = context.Variable(perVertexOutputPointerType, StorageClass.Output); + SpvInstruction perVertexOutputPointerType = context.TypePointer(StorageClass.Output, perVertexOutputArrayType); + SpvInstruction perVertexOutputVariable = context.Variable(perVertexOutputPointerType, StorageClass.Output); context.AddGlobalVariable(perVertexOutputVariable); context.Outputs.Add(new IoDefinition(StorageKind.Output, IoVariable.Position), perVertexOutputVariable); @@ -449,12 +449,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static SpvInstruction CreatePerVertexStructType(CodeGenContext context) { - var vec4FloatType = context.TypeVector(context.TypeFP32(), 4); - var floatType = context.TypeFP32(); - var array8FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 8)); - var array1FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 1)); + SpvInstruction vec4FloatType = context.TypeVector(context.TypeFP32(), 4); + SpvInstruction floatType = context.TypeFP32(); + SpvInstruction array8FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 8)); + SpvInstruction array1FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 1)); - var perVertexStructType = context.TypeStruct(true, vec4FloatType, floatType, array8FloatType, array1FloatType); + SpvInstruction perVertexStructType = context.TypeStruct(true, vec4FloatType, floatType, array8FloatType, array1FloatType); context.Name(perVertexStructType, "gl_PerVertex"); @@ -487,7 +487,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv int firstLocation = 0) { IoVariable ioVariable = ioDefinition.IoVariable; - var storageClass = isOutput ? StorageClass.Output : StorageClass.Input; + StorageClass storageClass = isOutput ? StorageClass.Output : StorageClass.Input; bool isBuiltIn; BuiltIn builtIn = default; @@ -532,7 +532,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv }; } - var spvType = context.GetType(varType, IoMap.GetSpirvBuiltInArrayLength(ioVariable)); + SpvInstruction spvType = context.GetType(varType, IoMap.GetSpirvBuiltInArrayLength(ioVariable)); bool builtInPassthrough = false; if (!isPerPatch && IoMap.IsPerVertex(ioVariable, context.Definitions.Stage, isOutput)) @@ -551,8 +551,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv spvType = context.TypeArray(spvType, context.Constant(context.TypeU32(), context.Definitions.ThreadsPerInputPrimitive)); } - var spvPointerType = context.TypePointer(storageClass, spvType); - var spvVar = context.Variable(spvPointerType, storageClass); + SpvInstruction spvPointerType = context.TypePointer(storageClass, spvType); + SpvInstruction spvVar = context.Variable(spvPointerType, storageClass); if (builtInPassthrough) { @@ -641,7 +641,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv ioVariable, ioDefinition.Location, ioDefinition.Component, - out var transformFeedbackOutput)) + out TransformFeedbackOutput transformFeedbackOutput)) { context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)transformFeedbackOutput.Buffer); context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)transformFeedbackOutput.Stride); @@ -650,7 +650,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv context.AddGlobalVariable(spvVar); - var dict = isPerPatch + Dictionary dict = isPerPatch ? (isOutput ? context.OutputsPerPatch : context.InputsPerPatch) : (isOutput ? context.Outputs : context.Inputs); dict.Add(ioDefinition, spvVar); diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs index 01940d857..8bae96ef7 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs @@ -153,7 +153,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public static OperationResult Generate(CodeGenContext context, AstOperation operation) { - var handler = _instTable[(int)(operation.Inst & Instruction.Mask)]; + Func handler = _instTable[(int)(operation.Inst & Instruction.Mask)]; if (handler != null) { return handler(context, operation); @@ -226,13 +226,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateBallot(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); - var uvec4Type = context.TypeVector(context.TypeU32(), 4); - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction uvec4Type = context.TypeVector(context.TypeU32(), 4); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var maskVector = context.GroupNonUniformBallot(uvec4Type, execution, context.Get(AggregateType.Bool, source)); - var mask = context.CompositeExtract(context.TypeU32(), maskVector, (SpvLiteralInteger)operation.Index); + SpvInstruction maskVector = context.GroupNonUniformBallot(uvec4Type, execution, context.Get(AggregateType.Bool, source)); + SpvInstruction mask = context.CompositeExtract(context.TypeU32(), maskVector, (SpvLiteralInteger)operation.Index); return new OperationResult(AggregateType.U32, mask); } @@ -308,21 +308,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Debug.Assert(funcId.Type == OperandType.Constant); - var (function, spvFunc) = context.GetFunction(funcId.Value); + (StructuredFunction function, SpvInstruction spvFunc) = context.GetFunction(funcId.Value); - var args = new SpvInstruction[operation.SourcesCount - 1]; + SpvInstruction[] args = new SpvInstruction[operation.SourcesCount - 1]; for (int i = 0; i < args.Length; i++) { - var operand = operation.GetSource(i + 1); + IAstNode operand = operation.GetSource(i + 1); AstOperand local = (AstOperand)operand; Debug.Assert(local.Type == OperandType.LocalVariable); args[i] = context.GetLocalPointer(local); } - var retType = function.ReturnType; - var result = context.FunctionCall(context.GetType(retType), spvFunc, args); + AggregateType retType = function.ReturnType; + SpvInstruction result = context.FunctionCall(context.GetType(retType), spvFunc, args); return new OperationResult(retType, result); } @@ -398,11 +398,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateConditionalSelect(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); - var cond = context.Get(AggregateType.Bool, src1); + SpvInstruction cond = context.Get(AggregateType.Bool, src1); if (operation.Inst.HasFlag(Instruction.FP64)) { @@ -420,70 +420,70 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateConvertFP32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.FConvert(context.TypeFP64(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP32ToS32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP32ToU32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP64ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.FConvert(context.TypeFP32(), context.GetFP64(source))); } private static OperationResult GenerateConvertFP64ToS32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP64(source))); } private static OperationResult GenerateConvertFP64ToU32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP64(source))); } private static OperationResult GenerateConvertS32ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.ConvertSToF(context.TypeFP32(), context.GetS32(source))); } private static OperationResult GenerateConvertS32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.ConvertSToF(context.TypeFP64(), context.GetS32(source))); } private static OperationResult GenerateConvertU32ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.ConvertUToF(context.TypeFP32(), context.GetU32(source))); } private static OperationResult GenerateConvertU32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.ConvertUToF(context.TypeFP64(), context.GetU32(source))); } @@ -555,19 +555,19 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateFindLSB(CodeGenContext context, AstOperation operation) { - var source = context.GetU32(operation.GetSource(0)); + SpvInstruction source = context.GetU32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindILsb(context.TypeU32(), source)); } private static OperationResult GenerateFindMSBS32(CodeGenContext context, AstOperation operation) { - var source = context.GetS32(operation.GetSource(0)); + SpvInstruction source = context.GetS32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindSMsb(context.TypeU32(), source)); } private static OperationResult GenerateFindMSBU32(CodeGenContext context, AstOperation operation) { - var source = context.GetU32(operation.GetSource(0)); + SpvInstruction source = context.GetU32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindUMsb(context.TypeU32(), source)); } @@ -608,7 +608,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstTextureOperation texOp = (AstTextureOperation)operation; - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); bool isArray = (texOp.Type & SamplerType.Array) != 0; @@ -648,7 +648,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -658,11 +658,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv SpvInstruction value = Src(componentType); - var pointer = context.ImageTexelPointer(imagePointerType, image, pCoords, context.Constant(context.TypeU32(), 0)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction pointer = context.ImageTexelPointer(imagePointerType, image, pCoords, context.Constant(context.TypeU32(), 0)); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); - var result = (texOp.Flags & TextureFlags.AtomicMask) switch + SpvInstruction result = (texOp.Flags & TextureFlags.AtomicMask) switch { TextureFlags.Add => context.AtomicIAdd(resultType, pointer, one, zero, value), TextureFlags.Minimum => componentType == AggregateType.S32 @@ -688,7 +688,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstTextureOperation texOp = (AstTextureOperation)operation; - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); bool isArray = (texOp.Type & SamplerType.Array) != 0; @@ -732,7 +732,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -740,11 +740,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.S32); } - var imageComponentType = context.GetType(componentType); - var swizzledResultType = texOp.GetVectorType(componentType); + SpvInstruction imageComponentType = context.GetType(componentType); + AggregateType swizzledResultType = texOp.GetVectorType(componentType); - var texel = context.ImageRead(context.TypeVector(imageComponentType, 4), image, pCoords, ImageOperandsMask.MaskNone); - var result = GetSwizzledResult(context, texel, swizzledResultType, texOp.Index); + SpvInstruction texel = context.ImageRead(context.TypeVector(imageComponentType, 4), image, pCoords, ImageOperandsMask.MaskNone); + SpvInstruction result = GetSwizzledResult(context, texel, swizzledResultType, texOp.Index); return new OperationResult(componentType, result); } @@ -795,7 +795,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -803,7 +803,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.S32); } - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); const int ComponentsCount = 4; @@ -826,7 +826,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var texel = context.CompositeConstruct(context.TypeVector(context.GetType(componentType), ComponentsCount), cElems); + SpvInstruction texel = context.CompositeConstruct(context.TypeVector(context.GetType(componentType), ComponentsCount), cElems); context.ImageWrite(image, pCoords, texel, ImageOperandsMask.MaskNone); @@ -835,7 +835,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateIsNan(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); SpvInstruction result; @@ -883,7 +883,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.FP32); } - var vectorType = context.TypeVector(context.TypeFP32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeFP32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -891,9 +891,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.FP32); } - var resultType = context.TypeVector(context.TypeFP32(), 2); - var packed = context.ImageQueryLod(resultType, image, pCoords); - var result = context.CompositeExtract(context.TypeFP32(), packed, (SpvLiteralInteger)texOp.Index); + SpvInstruction resultType = context.TypeVector(context.TypeFP32(), 2); + SpvInstruction packed = context.ImageQueryLod(resultType, image, pCoords); + SpvInstruction result = context.CompositeExtract(context.TypeFP32(), packed, (SpvLiteralInteger)texOp.Index); return new OperationResult(AggregateType.FP32, result); } @@ -989,11 +989,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateMultiplyHighS32(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var resultType = context.TypeStruct(false, context.TypeS32(), context.TypeS32()); - var result = context.SMulExtended(resultType, context.GetS32(src1), context.GetS32(src2)); + SpvInstruction resultType = context.TypeStruct(false, context.TypeS32(), context.TypeS32()); + SpvInstruction result = context.SMulExtended(resultType, context.GetS32(src1), context.GetS32(src2)); result = context.CompositeExtract(context.TypeS32(), result, 1); return new OperationResult(AggregateType.S32, result); @@ -1001,11 +1001,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateMultiplyHighU32(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var resultType = context.TypeStruct(false, context.TypeU32(), context.TypeU32()); - var result = context.UMulExtended(resultType, context.GetU32(src1), context.GetU32(src2)); + SpvInstruction resultType = context.TypeStruct(false, context.TypeU32(), context.TypeU32()); + SpvInstruction result = context.UMulExtended(resultType, context.GetU32(src1), context.GetU32(src2)); result = context.CompositeExtract(context.TypeU32(), result, 1); return new OperationResult(AggregateType.U32, result); @@ -1018,20 +1018,20 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GeneratePackDouble2x32(CodeGenContext context, AstOperation operation) { - var value0 = context.GetU32(operation.GetSource(0)); - var value1 = context.GetU32(operation.GetSource(1)); - var vector = context.CompositeConstruct(context.TypeVector(context.TypeU32(), 2), value0, value1); - var result = context.GlslPackDouble2x32(context.TypeFP64(), vector); + SpvInstruction value0 = context.GetU32(operation.GetSource(0)); + SpvInstruction value1 = context.GetU32(operation.GetSource(1)); + SpvInstruction vector = context.CompositeConstruct(context.TypeVector(context.TypeU32(), 2), value0, value1); + SpvInstruction result = context.GlslPackDouble2x32(context.TypeFP64(), vector); return new OperationResult(AggregateType.FP64, result); } private static OperationResult GeneratePackHalf2x16(CodeGenContext context, AstOperation operation) { - var value0 = context.GetFP32(operation.GetSource(0)); - var value1 = context.GetFP32(operation.GetSource(1)); - var vector = context.CompositeConstruct(context.TypeVector(context.TypeFP32(), 2), value0, value1); - var result = context.GlslPackHalf2x16(context.TypeU32(), vector); + SpvInstruction value0 = context.GetFP32(operation.GetSource(0)); + SpvInstruction value1 = context.GetFP32(operation.GetSource(1)); + SpvInstruction vector = context.CompositeConstruct(context.TypeVector(context.TypeFP32(), 2), value0, value1); + SpvInstruction result = context.GlslPackHalf2x16(context.TypeU32(), vector); return new OperationResult(AggregateType.U32, result); } @@ -1079,40 +1079,40 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateShuffle(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleDown(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleDown(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleDown(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleUp(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleUp(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleUp(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleXor(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleXor(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleXor(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } @@ -1139,31 +1139,31 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateSwizzleAdd(CodeGenContext context, AstOperation operation) { - var x = context.Get(AggregateType.FP32, operation.GetSource(0)); - var y = context.Get(AggregateType.FP32, operation.GetSource(1)); - var mask = context.Get(AggregateType.U32, operation.GetSource(2)); + SpvInstruction x = context.Get(AggregateType.FP32, operation.GetSource(0)); + SpvInstruction y = context.Get(AggregateType.FP32, operation.GetSource(1)); + SpvInstruction mask = context.Get(AggregateType.U32, operation.GetSource(2)); - var v4float = context.TypeVector(context.TypeFP32(), 4); - var one = context.Constant(context.TypeFP32(), 1.0f); - var minusOne = context.Constant(context.TypeFP32(), -1.0f); - var zero = context.Constant(context.TypeFP32(), 0.0f); - var xLut = context.ConstantComposite(v4float, one, minusOne, one, zero); - var yLut = context.ConstantComposite(v4float, one, one, minusOne, one); + SpvInstruction v4float = context.TypeVector(context.TypeFP32(), 4); + SpvInstruction one = context.Constant(context.TypeFP32(), 1.0f); + SpvInstruction minusOne = context.Constant(context.TypeFP32(), -1.0f); + SpvInstruction zero = context.Constant(context.TypeFP32(), 0.0f); + SpvInstruction xLut = context.ConstantComposite(v4float, one, minusOne, one, zero); + SpvInstruction yLut = context.ConstantComposite(v4float, one, one, minusOne, one); - var three = context.Constant(context.TypeU32(), 3); + SpvInstruction three = context.Constant(context.TypeU32(), 3); - var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId); - var shift = context.BitwiseAnd(context.TypeU32(), threadId, three); + SpvInstruction threadId = GetScalarInput(context, IoVariable.SubgroupLaneId); + SpvInstruction shift = context.BitwiseAnd(context.TypeU32(), threadId, three); shift = context.ShiftLeftLogical(context.TypeU32(), shift, context.Constant(context.TypeU32(), 1)); - var lutIdx = context.ShiftRightLogical(context.TypeU32(), mask, shift); + SpvInstruction lutIdx = context.ShiftRightLogical(context.TypeU32(), mask, shift); lutIdx = context.BitwiseAnd(context.TypeU32(), lutIdx, three); - var xLutValue = context.VectorExtractDynamic(context.TypeFP32(), xLut, lutIdx); - var yLutValue = context.VectorExtractDynamic(context.TypeFP32(), yLut, lutIdx); + SpvInstruction xLutValue = context.VectorExtractDynamic(context.TypeFP32(), xLut, lutIdx); + SpvInstruction yLutValue = context.VectorExtractDynamic(context.TypeFP32(), yLut, lutIdx); - var xResult = context.FMul(context.TypeFP32(), x, xLutValue); - var yResult = context.FMul(context.TypeFP32(), y, yLutValue); - var result = context.FAdd(context.TypeFP32(), xResult, yResult); + SpvInstruction xResult = context.FMul(context.TypeFP32(), x, xLutValue); + SpvInstruction yResult = context.FMul(context.TypeFP32(), y, yLutValue); + SpvInstruction result = context.FAdd(context.TypeFP32(), xResult, yResult); return new OperationResult(AggregateType.FP32, result); } @@ -1230,7 +1230,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var vectorType = context.TypeVector(intCoords ? context.TypeS32() : context.TypeFP32(), count); + SpvInstruction vectorType = context.TypeVector(intCoords ? context.TypeS32() : context.TypeFP32(), count); return context.CompositeConstruct(vectorType, elems); } else @@ -1252,7 +1252,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[index] = Src(AggregateType.FP32); } - var vectorType = context.TypeVector(context.TypeFP32(), count); + SpvInstruction vectorType = context.TypeVector(context.TypeFP32(), count); return context.CompositeConstruct(vectorType, elems); } else @@ -1302,7 +1302,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[index] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), count); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), count); return context.ConstantComposite(vectorType, elems); } @@ -1357,8 +1357,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv compIdx = Src(AggregateType.S32); } - var operandsList = new List(); - var operandsMask = ImageOperandsMask.MaskNone; + List operandsList = new(); + ImageOperandsMask operandsMask = ImageOperandsMask.MaskNone; if (hasLodBias) { @@ -1399,14 +1399,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv bool colorIsVector = isGather || !isShadow; - var resultType = colorIsVector ? context.TypeVector(context.TypeFP32(), 4) : context.TypeFP32(); + SpvInstruction resultType = colorIsVector ? context.TypeVector(context.TypeFP32(), 4) : context.TypeFP32(); if (intCoords) { image = context.Image(declaration.ImageType, image); } - var operands = operandsList.ToArray(); + SpvInstruction[] operands = operandsList.ToArray(); SpvInstruction result; @@ -1445,7 +1445,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv result = context.ImageSampleImplicitLod(resultType, image, pCoords, operandsMask, operands); } - var swizzledResultType = AggregateType.FP32; + AggregateType swizzledResultType = AggregateType.FP32; if (colorIsVector) { @@ -1490,7 +1490,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var type = context.SamplersTypes[texOp.GetTextureSetAndBinding()]; + SamplerType type = context.SamplersTypes[texOp.GetTextureSetAndBinding()]; bool hasLod = !type.HasFlag(SamplerType.Multisample) && type != SamplerType.TextureBuffer; int dimensions = (type & SamplerType.Mask) == SamplerType.TextureCube ? 2 : type.GetDimensions(); @@ -1500,13 +1500,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv dimensions++; } - var resultType = dimensions == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), dimensions); + SpvInstruction resultType = dimensions == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), dimensions); SpvInstruction result; if (hasLod) { - var lod = context.GetS32(operation.GetSource(srcIndex)); + SpvInstruction lod = context.GetS32(operation.GetSource(srcIndex)); result = context.ImageQuerySizeLod(resultType, image, lod); } else @@ -1530,27 +1530,27 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateUnpackDouble2x32(CodeGenContext context, AstOperation operation) { - var value = context.GetFP64(operation.GetSource(0)); - var vector = context.GlslUnpackDouble2x32(context.TypeVector(context.TypeU32(), 2), value); - var result = context.CompositeExtract(context.TypeU32(), vector, operation.Index); + SpvInstruction value = context.GetFP64(operation.GetSource(0)); + SpvInstruction vector = context.GlslUnpackDouble2x32(context.TypeVector(context.TypeU32(), 2), value); + SpvInstruction result = context.CompositeExtract(context.TypeU32(), vector, operation.Index); return new OperationResult(AggregateType.U32, result); } private static OperationResult GenerateUnpackHalf2x16(CodeGenContext context, AstOperation operation) { - var value = context.GetU32(operation.GetSource(0)); - var vector = context.GlslUnpackHalf2x16(context.TypeVector(context.TypeFP32(), 2), value); - var result = context.CompositeExtract(context.TypeFP32(), vector, operation.Index); + SpvInstruction value = context.GetU32(operation.GetSource(0)); + SpvInstruction vector = context.GlslUnpackHalf2x16(context.TypeVector(context.TypeFP32(), 2), value); + SpvInstruction result = context.CompositeExtract(context.TypeFP32(), vector, operation.Index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateVectorExtract(CodeGenContext context, AstOperation operation) { - var vector = context.GetWithType(operation.GetSource(0), out AggregateType vectorType); - var scalarType = vectorType & ~AggregateType.ElementCountMask; - var resultType = context.GetType(scalarType); + SpvInstruction vector = context.GetWithType(operation.GetSource(0), out AggregateType vectorType); + AggregateType scalarType = vectorType & ~AggregateType.ElementCountMask; + SpvInstruction resultType = context.GetType(scalarType); SpvInstruction result; if (operation.GetSource(1) is AstOperand indexOperand && indexOperand.Type == OperandType.Constant) @@ -1559,7 +1559,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var index = context.Get(AggregateType.S32, operation.GetSource(1)); + SpvInstruction index = context.Get(AggregateType.S32, operation.GetSource(1)); result = context.VectorExtractDynamic(resultType, vector, index); } @@ -1568,22 +1568,22 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateVoteAll(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAll(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAll(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } private static OperationResult GenerateVoteAllEqual(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAllEqual(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAllEqual(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } private static OperationResult GenerateVoteAny(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAny(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAny(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } @@ -1593,8 +1593,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); SpvInstruction result; @@ -1619,10 +1619,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var result = emitU(context.TypeBool(), context.GetU32(src1), context.GetU32(src2)); + SpvInstruction result = emitU(context.TypeBool(), context.GetU32(src1), context.GetU32(src2)); return new OperationResult(AggregateType.Bool, result); } @@ -1634,10 +1634,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { SpvInstruction elemPointer = GetStoragePointer(context, operation, out AggregateType varType); - var value = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); + SpvInstruction value = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); return new OperationResult(varType, emitU(context.GetType(varType), elemPointer, one, zero, value)); } @@ -1646,11 +1646,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { SpvInstruction elemPointer = GetStoragePointer(context, operation, out AggregateType varType); - var value0 = context.Get(varType, operation.GetSource(operation.SourcesCount - 2)); - var value1 = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); + SpvInstruction value0 = context.Get(varType, operation.GetSource(operation.SourcesCount - 2)); + SpvInstruction value1 = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); return new OperationResult(varType, context.AtomicCompareExchange(context.GetType(varType), elemPointer, one, zero, zero, value1, value0)); } @@ -1666,7 +1666,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var result = context.Load(context.GetType(varType), pointer); + SpvInstruction result = context.Load(context.GetType(varType), pointer); return new OperationResult(varType, result); } } @@ -1784,8 +1784,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv storageClass = isOutput ? StorageClass.Output : StorageClass.Input; - var ioDefinition = new IoDefinition(storageKind, ioVariable, location, component); - var dict = isPerPatch + IoDefinition ioDefinition = new(storageKind, ioVariable, location, component); + Dictionary dict = isPerPatch ? (isOutput ? context.OutputsPerPatch : context.InputsPerPatch) : (isOutput ? context.Outputs : context.Inputs); @@ -1803,7 +1803,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { int fieldIndex = IoMap.GetPerVertexStructFieldIndex(perVertexBuiltIn.Value); - var indexes = new SpvInstruction[inputsCount + 1]; + SpvInstruction[] indexes = new SpvInstruction[inputsCount + 1]; int index = 0; if (IoMap.IsPerVertexArrayBuiltIn(storageKind, context.Definitions.Stage)) @@ -1853,7 +1853,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, e0, e1, e2); break; default: - var indexes = new SpvInstruction[inputsCount]; + SpvInstruction[] indexes = new SpvInstruction[inputsCount]; int index = 0; for (; index < inputsCount; srcIndex++, index++) @@ -1870,10 +1870,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static SpvInstruction GetScalarInput(CodeGenContext context, IoVariable ioVariable) { - var (_, varType) = IoMap.GetSpirvBuiltIn(ioVariable); + (_, AggregateType varType) = IoMap.GetSpirvBuiltIn(ioVariable); varType &= AggregateType.ElementTypeMask; - var ioDefinition = new IoDefinition(StorageKind.Input, ioVariable); + IoDefinition ioDefinition = new(StorageKind.Input, ioVariable); return context.Load(context.GetType(varType), context.Inputs[ioDefinition]); } @@ -1968,7 +1968,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); if (operation.Inst.HasFlag(Instruction.FP64)) { @@ -1989,7 +1989,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitB) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, source))); } @@ -1998,7 +1998,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emit) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, emit(context.TypeFP32(), context.GetFP32(source))); } @@ -2007,7 +2007,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(source))); } @@ -2017,12 +2017,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); if (operation.Inst.HasFlag(Instruction.FP64)) { - var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2)); + SpvInstruction result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2033,7 +2033,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (operation.Inst.HasFlag(Instruction.FP32)) { - var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2)); + SpvInstruction result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2053,8 +2053,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitB) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, src1), context.Get(AggregateType.Bool, src2))); } @@ -2064,8 +2064,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(src1), context.GetS32(src2))); } @@ -2075,8 +2075,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.U32, emitU(context.TypeU32(), context.GetU32(src1), context.GetU32(src2))); } @@ -2087,13 +2087,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); if (operation.Inst.HasFlag(Instruction.FP64)) { - var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2), context.GetFP64(src3)); + SpvInstruction result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2), context.GetFP64(src3)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2104,7 +2104,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (operation.Inst.HasFlag(Instruction.FP32)) { - var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2), context.GetFP32(src3)); + SpvInstruction result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2), context.GetFP32(src3)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2124,9 +2124,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); return new OperationResult(AggregateType.U32, emitU( context.TypeU32(), @@ -2140,9 +2140,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); return new OperationResult(AggregateType.S32, emitS( context.TypeS32(), @@ -2156,10 +2156,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); - var src4 = operation.GetSource(3); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); + IAstNode src4 = operation.GetSource(3); return new OperationResult(AggregateType.U32, emitS( context.TypeU32(), diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs index b2527f91b..104f5ef8a 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs @@ -129,20 +129,20 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++) { - var function = info.Functions[funcIndex]; - var retType = context.GetType(function.ReturnType); + StructuredFunction function = info.Functions[funcIndex]; + SpvInstruction retType = context.GetType(function.ReturnType); - var funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length]; + SpvInstruction[] funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length]; for (int argIndex = 0; argIndex < funcArgs.Length; argIndex++) { - var argType = context.GetType(function.GetArgumentType(argIndex)); - var argPointerType = context.TypePointer(StorageClass.Function, argType); + SpvInstruction argType = context.GetType(function.GetArgumentType(argIndex)); + SpvInstruction argPointerType = context.TypePointer(StorageClass.Function, argType); funcArgs[argIndex] = argPointerType; } - var funcType = context.TypeFunction(retType, false, funcArgs); - var spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType); + SpvInstruction funcType = context.TypeFunction(retType, false, funcArgs); + SpvInstruction spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType); context.DeclareFunction(funcIndex, function, spvFunc); } @@ -165,7 +165,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void Generate(CodeGenContext context, StructuredProgramInfo info, int funcIndex) { - var (function, spvFunc) = context.GetFunction(funcIndex); + (StructuredFunction function, SpvInstruction spvFunc) = context.GetFunction(funcIndex); context.CurrentFunction = function; context.AddFunction(spvFunc); @@ -289,9 +289,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (context.Definitions.Stage == ShaderStage.Compute) { - var localSizeX = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeX; - var localSizeY = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeY; - var localSizeZ = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeZ; + SpvLiteralInteger localSizeX = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeX; + SpvLiteralInteger localSizeY = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeY; + SpvLiteralInteger localSizeZ = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeZ; context.AddExecutionMode( spvFunc, @@ -312,7 +312,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstBlockVisitor visitor = new(block); - var loopTargets = new Dictionary(); + Dictionary loopTargets = new(); context.LoopTargets = loopTargets; @@ -334,14 +334,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv ifFalseBlock = mergeBlock; } - var condition = context.Get(AggregateType.Bool, e.Block.Condition); + SpvInstruction condition = context.Get(AggregateType.Bool, e.Block.Condition); context.SelectionMerge(context.GetNextLabel(mergeBlock), SelectionControlMask.MaskNone); context.BranchConditional(condition, context.GetNextLabel(ifTrueBlock), context.GetNextLabel(ifFalseBlock)); } else if (e.Block.Type == AstBlockType.DoWhile) { - var continueTarget = context.Label(); + SpvInstruction continueTarget = context.Label(); loopTargets.Add(e.Block, (context.NewBlock(), continueTarget)); @@ -362,12 +362,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv // if the condition is true. AstBlock mergeBlock = e.Block.Parent; - var (loopTarget, continueTarget) = loopTargets[e.Block]; + (SpvInstruction loopTarget, SpvInstruction continueTarget) = loopTargets[e.Block]; context.Branch(continueTarget); context.AddLabel(continueTarget); - var condition = context.Get(AggregateType.Bool, e.Block.Condition); + SpvInstruction condition = context.Get(AggregateType.Bool, e.Block.Condition); context.BranchConditional(condition, loopTarget, context.GetNextLabel(mergeBlock)); } @@ -402,16 +402,16 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstAssignment assignment) { - var dest = (AstOperand)assignment.Destination; + AstOperand dest = (AstOperand)assignment.Destination; if (dest.Type == OperandType.LocalVariable) { - var source = context.Get(dest.VarType, assignment.Source); + SpvInstruction source = context.Get(dest.VarType, assignment.Source); context.Store(context.GetLocalPointer(dest), source); } else if (dest.Type == OperandType.Argument) { - var source = context.Get(dest.VarType, assignment.Source); + SpvInstruction source = context.Get(dest.VarType, assignment.Source); context.Store(context.GetArgumentPointer(dest), source); } else diff --git a/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs b/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs index 2718677e2..0f9161cf8 100644 --- a/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs +++ b/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs @@ -568,39 +568,39 @@ namespace Ryujinx.Graphics.Shader.Decoders HashSet visited = []; - var ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg); + BlockLocation ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg); if (ldcLocation.Block == null || ldcLocation.Block.OpCodes[ldcLocation.Index].Name != InstName.Ldc) { return (0, 0); } - GetOp(ldcLocation, out var opLdc); + GetOp(ldcLocation, out InstLdc opLdc); if (opLdc.CbufSlot != 1 || opLdc.AddressMode != 0) { return (0, 0); } - var shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.SrcA); + BlockLocation shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.SrcA); if (shlLocation.Block == null || !shlLocation.IsImmInst(InstName.Shl)) { return (0, 0); } - GetOp(shlLocation, out var opShl); + GetOp(shlLocation, out InstShlI opShl); if (opShl.Imm20 != 2) { return (0, 0); } - var imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.SrcA); + BlockLocation imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.SrcA); if (imnmxLocation.Block == null || !imnmxLocation.IsImmInst(InstName.Imnmx)) { return (0, 0); } - GetOp(imnmxLocation, out var opImnmx); + GetOp(imnmxLocation, out InstImnmxI opImnmx); if (opImnmx.Signed || opImnmx.SrcPred != RegisterConsts.PredicateTrueIndex || opImnmx.SrcPredInv) { @@ -640,7 +640,7 @@ namespace Ryujinx.Graphics.Shader.Decoders toVisit.Enqueue(location); visited.Add(location.Block); - while (toVisit.TryDequeue(out var currentLocation)) + while (toVisit.TryDequeue(out BlockLocation currentLocation)) { Block block = currentLocation.Block; for (int i = currentLocation.Index - 1; i >= 0; i--) diff --git a/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs b/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs index a61c3f300..5f505b03f 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static IReadOnlyDictionary CreateMap() { - var map = new Dictionary(); + Dictionary map = new(); Add(map, 0x060, AggregateType.S32, IoVariable.PrimitiveId, StagesMask.TessellationGeometryFragment, StagesMask.Geometry); Add(map, 0x064, AggregateType.S32, IoVariable.Layer, StagesMask.Fragment, StagesMask.VertexTessellationGeometry); @@ -84,7 +84,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static IReadOnlyDictionary CreatePerPatchMap() { - var map = new Dictionary(); + Dictionary map = new(); Add(map, 0x000, AggregateType.Vector4 | AggregateType.FP32, IoVariable.TessellationLevelOuter, StagesMask.TessellationEvaluation, StagesMask.TessellationControl); Add(map, 0x010, AggregateType.Vector2 | AggregateType.FP32, IoVariable.TessellationLevelInner, StagesMask.TessellationEvaluation, StagesMask.TessellationControl); diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs index 6606803cd..ec99446bd 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs @@ -261,7 +261,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { if (context.TranslatorContext.Definitions.LastInVertexPipeline) { - context.PrepareForVertexReturn(out var tempXLocal, out var tempYLocal, out var tempZLocal); + context.PrepareForVertexReturn(out Operand tempXLocal, out Operand tempYLocal, out Operand tempZLocal); context.EmitVertex(); diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs index 3a8419698..97b08aefd 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs @@ -13,8 +13,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -23,8 +23,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -43,9 +43,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitBfi(context, srcA, srcB, srcC, op.Dest); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs index 5a34cc755..b0c73def3 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fR op = context.GetOp(); - var src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); + Operand src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -23,7 +23,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fI op = context.GetOp(); - var src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); + Operand src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -32,7 +32,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fC op = context.GetOp(); - var src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); + Operand src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -41,7 +41,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iR op = context.GetOp(); - var src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); + Operand src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -50,7 +50,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iI op = context.GetOp(); - var src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); + Operand src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -59,7 +59,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iC op = context.GetOp(); - var src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); + Operand src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fR op = context.GetOp(); - var src = GetSrcReg(context, op.SrcB); + Operand src = GetSrcReg(context, op.SrcB); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fI op = context.GetOp(); - var src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -86,7 +86,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fC op = context.GetOp(); - var src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iR op = context.GetOp(); - var src = GetSrcReg(context, op.SrcB); + Operand src = GetSrcReg(context, op.SrcB); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iI op = context.GetOp(); - var src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } @@ -113,7 +113,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iC op = context.GetOp(); - var src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs index 04dbd20eb..7d974a370 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs @@ -13,8 +13,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -23,8 +23,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -43,9 +43,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcC, isFP64: true); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -87,8 +87,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -97,8 +97,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -107,8 +107,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -117,8 +117,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -127,8 +127,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -137,8 +137,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -147,8 +147,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -157,9 +157,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -168,9 +168,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -179,9 +179,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -190,9 +190,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -201,9 +201,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfma32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); - var srcC = GetSrcReg(context, op.Dest); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); + Operand srcC = GetSrcReg(context, op.Dest); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -212,8 +212,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -222,8 +222,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -232,8 +232,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmul32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitFmul(context, Instruction.FP32, MultiplyScale.NoScale, srcA, srcB, op.Dest, false, op.Sat, op.WriteCC); } @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -262,8 +262,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -272,8 +272,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -282,8 +282,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, false); - var srcB = GetHalfSrc(context, op.Imm); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, false); + Operand[] srcB = GetHalfSrc(context, op.Imm); EmitHadd2Hmul2(context, OFmt.F16, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -292,9 +292,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, false); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -303,9 +303,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -314,9 +314,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, false); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -325,9 +325,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2Rc op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegA, false); - var srcC = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -336,9 +336,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.Imm); - var srcC = GetHalfSrc(context, HalfSwizzle.F16, op.Dest, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.Imm); + Operand[] srcC = GetHalfSrc(context, HalfSwizzle.F16, op.Dest, op.NegC, false); EmitHfma2(context, OFmt.F16, srcA, srcB, srcC, op.Dest, saturate: false); } @@ -347,8 +347,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -357,8 +357,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -367,8 +367,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -377,8 +377,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.Imm32); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.Imm32); EmitHadd2Hmul2(context, OFmt.F16, srcA, srcB, isAdd: false, op.Dest, op.Sat); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs index 46ac84c96..e70afd74c 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs @@ -14,8 +14,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFset( context, @@ -39,8 +39,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFset( context, @@ -64,8 +64,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFset( context, @@ -89,8 +89,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFsetp( context, @@ -114,8 +114,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFsetp( context, @@ -139,8 +139,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFsetp( context, @@ -164,9 +164,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -175,9 +175,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -186,9 +186,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -197,9 +197,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -208,8 +208,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -218,8 +218,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -228,8 +228,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -238,8 +238,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFsetp( context, @@ -262,8 +262,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFsetp( context, @@ -286,8 +286,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFsetp( context, @@ -310,8 +310,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -320,8 +320,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -330,8 +330,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, false); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -340,8 +340,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHsetp2(context, op.FComp2, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -350,8 +350,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHsetp2(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -360,8 +360,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); EmitHsetp2(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -545,7 +545,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else { - var inst = (cond & ~FComp.Nan) switch + Instruction inst = (cond & ~FComp.Nan) switch { FComp.Lt => Instruction.CompareLess, FComp.Eq => Instruction.CompareEqual, diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs index 5757e4fb0..4a3337bca 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -46,9 +46,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } @@ -57,9 +57,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } @@ -68,9 +68,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs index 803aaa62d..e86328868 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs @@ -39,13 +39,13 @@ namespace Ryujinx.Graphics.Shader.Instructions Operand address = context.IAdd(Register(op.SrcA, RegisterType.Gpr), Const(offset)); - var targets = context.CurrBlock.Successors.Skip(startIndex); + IEnumerable targets = context.CurrBlock.Successors.Skip(startIndex); bool allTargetsSinglePred = true; int total = context.CurrBlock.Successors.Count - startIndex; int count = 0; - foreach (var target in targets.OrderBy(x => x.Address)) + foreach (Block target in targets.OrderBy(x => x.Address)) { if (++count < total && (target.Predecessors.Count > 1 || target.Address <= context.CurrBlock.Address)) { @@ -64,7 +64,7 @@ namespace Ryujinx.Graphics.Shader.Instructions // since it will be too late to insert a label, but this is something that can be improved // in the future if necessary. - var sortedTargets = targets.OrderBy(x => x.Address); + IOrderedEnumerable sortedTargets = targets.OrderBy(x => x.Address); Block currentTarget = null; ulong firstTargetAddress = 0; @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Shader.Instructions // Emit the branches sequentially. // This generates slightly worse code, but should work for all cases. - var sortedTargets = targets.OrderByDescending(x => x.Address); + IOrderedEnumerable sortedTargets = targets.OrderByDescending(x => x.Address); ulong lastTargetAddress = ulong.MaxValue; count = 0; @@ -238,7 +238,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static void EmitPbkPcntSsy(EmitterContext context) { - var consumers = context.CurrBlock.PushOpCodes.First(x => x.Op.Address == context.CurrOp.Address).Consumers; + Dictionary consumers = context.CurrBlock.PushOpCodes.First(x => x.Op.Address == context.CurrOp.Address).Consumers; foreach (KeyValuePair kv in consumers) { @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static void EmitBrkContSync(EmitterContext context) { - var targets = context.CurrBlock.SyncTargets; + Dictionary targets = context.CurrBlock.SyncTargets; if (targets.Count == 1) { diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs index 99922f7a1..2f3988119 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs @@ -14,8 +14,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -24,8 +24,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -34,8 +34,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -44,8 +44,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3R op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, op.Lrs, srcA, srcB, srcC, op.Apart, op.Bpart, op.Cpart, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3I op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, Lrs.None, srcA, srcB, srcC, HalfSelect.B32, HalfSelect.B32, HalfSelect.B32, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3C op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, Lrs.None, srcA, srcB, srcC, HalfSelect.B32, HalfSelect.B32, HalfSelect.B32, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -87,9 +87,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -98,9 +98,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -109,9 +109,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -120,9 +120,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -131,9 +131,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImad32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); - var srcC = GetSrcReg(context, op.Dest); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); + Operand srcC = GetSrcReg(context, op.Dest); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -142,8 +142,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -152,8 +152,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -162,8 +162,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -172,8 +172,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImul32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -182,8 +182,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -192,8 +192,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -202,8 +202,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -212,8 +212,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, AvgMode.NoNeg, op.WriteCC); } @@ -222,8 +222,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -232,8 +232,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -252,9 +252,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaHiR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLeaHi(context, srcA, srcB, srcC, op.Dest, op.NegA, op.ImmU5); } @@ -263,9 +263,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaHiC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLeaHi(context, srcA, srcB, srcC, op.Dest, op.NegA, op.ImmU5); } @@ -274,9 +274,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -285,9 +285,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm16); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm16); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, false, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -296,9 +296,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -307,9 +307,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, false, false, op.X, op.WriteCC); } @@ -578,7 +578,7 @@ namespace Ryujinx.Graphics.Shader.Instructions bool extended, bool writeCC) { - var srcBUnmodified = srcB; + Operand srcBUnmodified = srcB; Operand Extend16To32(Operand src, bool high, bool signed) { diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs index 18d4e3d19..c97e53bfe 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs @@ -14,9 +14,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -25,9 +25,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -36,9 +36,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -47,9 +47,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -58,8 +58,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -68,8 +68,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -78,8 +78,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -88,8 +88,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -98,8 +98,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -108,8 +108,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -280,7 +280,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else { - var inst = cond switch + Instruction inst = cond switch { IComp.Lt => Instruction.CompareLessU32, IComp.Eq => Instruction.CompareEqual, diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs index 5993c93dd..2e2d951d2 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs @@ -15,8 +15,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitLop(context, op.Lop, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -25,8 +25,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitLop(context, op.LogicOp, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -35,8 +35,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitLop(context, op.LogicOp, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -45,8 +45,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitLop(context, op.LogicOp, PredicateOp.F, srcA, srcB, op.Dest, PT, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -55,9 +55,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3R op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, op.PredicateOp, srcA, srcB, srcC, op.Dest, op.DestPred, op.X, op.WriteCC); } @@ -66,9 +66,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3I op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, PredicateOp.F, srcA, srcB, srcC, op.Dest, PT, false, op.WriteCC); } @@ -77,9 +77,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3C op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, PredicateOp.F, srcA, srcB, srcC, op.Dest, PT, false, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs index 739e94413..f34efc6f3 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs index efa99dc3e..9c7899940 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfLR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: true, op.WriteCC); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfRR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: false, op.WriteCC); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfLI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = Const(op.Imm6); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = Const(op.Imm6); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: true, op.WriteCC); } @@ -46,9 +46,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfRI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = Const(op.Imm6); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = Const(op.Imm6); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: false, op.WriteCC); } @@ -78,8 +78,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } @@ -88,8 +88,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } @@ -98,8 +98,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs index abf11046f..4748dc483 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstTld op = context.GetOp(); - var lod = op.Lod ? Lod.Ll : Lod.Lz; + Lod lod = op.Lod ? Lod.Ll : Lod.Lz; EmitTex(context, TextureFlags.IntCoords, op.Dim, lod, op.TidB, op.WMask, op.SrcA, op.SrcB, op.Dest, op.Ms, false, op.Toff); } @@ -66,8 +66,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstTldB op = context.GetOp(); - var flags = TextureFlags.IntCoords | TextureFlags.Bindless; - var lod = op.Lod ? Lod.Ll : Lod.Lz; + TextureFlags flags = TextureFlags.IntCoords | TextureFlags.Bindless; + Lod lod = op.Lod ? Lod.Ll : Lod.Lz; EmitTex(context, flags, op.Dim, lod, 0, op.WMask, op.SrcA, op.SrcB, op.Dest, op.Ms, false, op.Toff); } @@ -374,7 +374,7 @@ namespace Ryujinx.Graphics.Shader.Instructions if (texsType == TexsType.Texs) { - var texsOp = context.GetOp(); + InstTexs texsOp = context.GetOp(); type = ConvertSamplerType(texsOp.Target); @@ -466,7 +466,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else if (texsType == TexsType.Tlds) { - var tldsOp = context.GetOp(); + InstTlds tldsOp = context.GetOp(); type = ConvertSamplerType(tldsOp.Target); @@ -560,7 +560,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else if (texsType == TexsType.Tld4s) { - var tld4sOp = context.GetOp(); + InstTld4s tld4sOp = context.GetOp(); if (!(tld4sOp.Dc || tld4sOp.Aoffi)) { diff --git a/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs b/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs index 165fce939..f0f22c056 100644 --- a/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs +++ b/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr return TextureFormat.Unknown; } - var format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); + TextureFormat format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); if (format == TextureFormat.Unknown) { @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr // Atomic image instructions do not support GL_EXT_shader_image_load_formatted, // and must have a type specified. Default to R32Sint if not available. - var format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); + TextureFormat format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); if (!FormatSupportsAtomic(format)) { diff --git a/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs b/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs index 9271f1cd7..56d8174c5 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.Shader.Decoders; using Ryujinx.Graphics.Shader.IntermediateRepresentation; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; @@ -256,8 +257,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int tfbIndex = 0; tfbIndex < ResourceReservations.TfeBuffersCount; tfbIndex++) { - var locations = TranslatorContext.GpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); - var stride = TranslatorContext.GpuAccessor.QueryTransformFeedbackStride(tfbIndex); + ReadOnlySpan locations = TranslatorContext.GpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); + int stride = TranslatorContext.GpuAccessor.QueryTransformFeedbackStride(tfbIndex); Operand baseOffset = this.Load(StorageKind.ConstantBuffer, SupportBuffer.Binding, Const((int)SupportBufferField.TfeOffset), Const(tfbIndex)); Operand baseVertex = this.Load(StorageKind.Input, IoVariable.BaseVertex); diff --git a/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs b/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs index ba1a3e1ab..7432cffa2 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs @@ -490,8 +490,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int index = 0; index < pTreeNode.Uses.Count; index++) { - var pUse = pTreeNode.Uses[index]; - var cUse = cTreeNode.Uses[index]; + PatternTreeNodeUse pUse = pTreeNode.Uses[index]; + TreeNodeUse cUse = cTreeNode.Uses[index]; if (pUse.Index <= -2) { @@ -524,8 +524,8 @@ namespace Ryujinx.Graphics.Shader.Translation { public static IPatternTreeNode[] GetFsiGetAddress() { - var affinityValue = S2r(SReg.Affinity).Use(PT).Out; - var orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; + PatternTreeNodeUse affinityValue = S2r(SReg.Affinity).Use(PT).Out; + PatternTreeNodeUse orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; return [ @@ -554,8 +554,8 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiGetAddressV2() { - var affinityValue = S2r(SReg.Affinity).Use(PT).Out; - var orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; + PatternTreeNodeUse affinityValue = S2r(SReg.Affinity).Use(PT).Out; + PatternTreeNodeUse orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; return [ @@ -582,8 +582,8 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiIsLastWarpThread() { - var threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; - var laneIdValue = S2r(SReg.LaneId).Use(PT).Out; + PatternTreeNodeUse threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; + PatternTreeNodeUse laneIdValue = S2r(SReg.LaneId).Use(PT).Out; return [ @@ -609,11 +609,11 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiBeginPattern() { - var addressLowValue = CallArg(1); + PatternTreeNodeUse addressLowValue = CallArg(1); static PatternTreeNodeUse HighU16Equals(PatternTreeNodeUse x) { - var expectedValue = CallArg(3); + PatternTreeNodeUse expectedValue = CallArg(3); return IsetpU32(IComp.Eq) .Use(PT) @@ -644,13 +644,13 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiEndPattern() { - var voteResult = Vote(VoteMode.All).Use(PT).Use(PT).OutAt(1); - var popcResult = Popc().Use(PT).Use(voteResult).Out; - var threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; - var laneIdValue = S2r(SReg.LaneId).Use(PT).Out; + PatternTreeNodeUse voteResult = Vote(VoteMode.All).Use(PT).Use(PT).OutAt(1); + PatternTreeNodeUse popcResult = Popc().Use(PT).Use(voteResult).Out; + PatternTreeNodeUse threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; + PatternTreeNodeUse laneIdValue = S2r(SReg.LaneId).Use(PT).Out; - var addressLowValue = CallArg(1); - var incrementValue = CallArg(2); + PatternTreeNodeUse addressLowValue = CallArg(1); + PatternTreeNodeUse incrementValue = CallArg(2); return [ diff --git a/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs b/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs index 811b22f50..fb29073a2 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs @@ -266,7 +266,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations { Operand value = operation.GetSource(operation.SourcesCount - 1); - var result = FindUniqueBaseAddressCb(gtsContext, block, value, needsOffset: false); + SearchResult result = FindUniqueBaseAddressCb(gtsContext, block, value, needsOffset: false); if (result.Found) { uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset); @@ -1017,7 +1017,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations offset = src1; } - var result = GetBaseAddressCbWithOffset(baseAddr, offset, 0); + SearchResult result = GetBaseAddressCbWithOffset(baseAddr, offset, 0); if (result.Found) { return result; diff --git a/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs b/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs index a63f9092a..ee7707275 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs @@ -302,7 +302,7 @@ namespace Ryujinx.Graphics.Shader.Translation Debug.Assert(funcId.Type == OperandType.Constant); - var fru = frus[funcId.Value]; + FunctionRegisterUsage fru = frus[funcId.Value]; Operand[] inRegs = new Operand[fru.InArguments.Length]; diff --git a/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs b/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs index f8ce14c42..1cbc16da5 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Shader.Translation size = DefaultLocalMemorySize; } - var lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); + MemoryDefinition lmem = new("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); LocalMemoryId = Properties.AddLocalMemory(lmem); } @@ -112,7 +112,7 @@ namespace Ryujinx.Graphics.Shader.Translation size = DefaultSharedMemorySize; } - var smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); + MemoryDefinition smem = new("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); SharedMemoryId = Properties.AddSharedMemory(smem); } @@ -273,16 +273,16 @@ namespace Ryujinx.Graphics.Shader.Translation bool coherent, bool separate) { - var dimensions = type == SamplerType.None ? 0 : type.GetDimensions(); - var dict = isImage ? _usedImages : _usedTextures; + int dimensions = type == SamplerType.None ? 0 : type.GetDimensions(); + Dictionary dict = isImage ? _usedImages : _usedTextures; - var usageFlags = TextureUsageFlags.None; + TextureUsageFlags usageFlags = TextureUsageFlags.None; if (intCoords) { usageFlags |= TextureUsageFlags.NeedsScaleValue; - var canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2; + bool canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2; if (!canScale) { @@ -304,9 +304,9 @@ namespace Ryujinx.Graphics.Shader.Translation // For array textures, we also want to use type as key, // since we may have texture handles stores in the same buffer, but for textures with different types. - var keyType = arrayLength > 1 ? type : SamplerType.None; - var info = new TextureInfo(cbufSlot, handle, arrayLength, separate, keyType, format); - var meta = new TextureMeta() + SamplerType keyType = arrayLength > 1 ? type : SamplerType.None; + TextureInfo info = new(cbufSlot, handle, arrayLength, separate, keyType, format); + TextureMeta meta = new() { AccurateType = accurateType, Type = type, @@ -316,7 +316,7 @@ namespace Ryujinx.Graphics.Shader.Translation int setIndex; int binding; - if (dict.TryGetValue(info, out var existingMeta)) + if (dict.TryGetValue(info, out TextureMeta existingMeta)) { dict[info] = MergeTextureMeta(meta, existingMeta); setIndex = existingMeta.Set; @@ -373,7 +373,7 @@ namespace Ryujinx.Graphics.Shader.Translation nameSuffix = cbufSlot < 0 ? $"{prefix}_tcb_{handle:X}" : $"{prefix}_cb{cbufSlot}_{handle:X}"; } - var definition = new TextureDefinition( + TextureDefinition definition = new( setIndex, binding, arrayLength, @@ -433,8 +433,8 @@ namespace Ryujinx.Graphics.Shader.Translation { selectedMeta.UsageFlags |= TextureUsageFlags.NeedsScaleValue; - var dimensions = type.GetDimensions(); - var canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2; + int dimensions = type.GetDimensions(); + bool canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2; if (!canScale) { @@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.Shader.Translation public BufferDescriptor[] GetConstantBufferDescriptors() { - var descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count]; + BufferDescriptor[] descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count]; int descriptorIndex = 0; @@ -478,7 +478,7 @@ namespace Ryujinx.Graphics.Shader.Translation public BufferDescriptor[] GetStorageBufferDescriptors() { - var descriptors = new BufferDescriptor[_sbSlots.Count]; + BufferDescriptor[] descriptors = new BufferDescriptor[_sbSlots.Count]; int descriptorIndex = 0; diff --git a/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs b/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs index f831ec940..656ad6c5e 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs @@ -192,7 +192,7 @@ namespace Ryujinx.Graphics.Shader.Translation component = subIndex; } - var transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); + TransformFeedbackVariable transformFeedbackVariable = new(ioVariable, location, component); _transformFeedbackDefinitions.TryAdd(transformFeedbackVariable, transformFeedbackOutputs[wordOffset]); } } @@ -219,7 +219,7 @@ namespace Ryujinx.Graphics.Shader.Translation return false; } - var transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); + TransformFeedbackVariable transformFeedbackVariable = new(ioVariable, location, component); return _transformFeedbackDefinitions.TryGetValue(transformFeedbackVariable, out transformFeedbackOutput); } @@ -271,8 +271,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (; count < 4; count++) { - ref var prev = ref _transformFeedbackOutputs[baseIndex + count - 1]; - ref var curr = ref _transformFeedbackOutputs[baseIndex + count]; + ref TransformFeedbackOutput prev = ref _transformFeedbackOutputs[baseIndex + count - 1]; + ref TransformFeedbackOutput curr = ref _transformFeedbackOutputs[baseIndex + count]; int prevOffset = prev.Offset; int currOffset = curr.Offset; diff --git a/src/Ryujinx.Graphics.Shader/Translation/Translator.cs b/src/Ryujinx.Graphics.Shader/Translation/Translator.cs index 54cad966a..2a1110632 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/Translator.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/Translator.cs @@ -110,8 +110,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int tfbIndex = 0; tfbIndex < 4; tfbIndex++) { - var locations = gpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); - var stride = gpuAccessor.QueryTransformFeedbackStride(tfbIndex); + ReadOnlySpan locations = gpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); + int stride = gpuAccessor.QueryTransformFeedbackStride(tfbIndex); for (int i = 0; i < locations.Length; i++) { diff --git a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs index 8d785fc5b..265b7be91 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs @@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Translation usedFeatures |= FeatureFlags.VtgAsCompute; } - var cfgs = new ControlFlowGraph[functions.Length]; - var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length]; + ControlFlowGraph[] cfgs = new ControlFlowGraph[functions.Length]; + RegisterUsage.FunctionRegisterUsage[] frus = new RegisterUsage.FunctionRegisterUsage[functions.Length]; for (int i = 0; i < functions.Length; i++) { @@ -266,14 +266,14 @@ namespace Ryujinx.Graphics.Shader.Translation for (int i = 0; i < functions.Length; i++) { - var cfg = cfgs[i]; + ControlFlowGraph cfg = cfgs[i]; int inArgumentsCount = 0; int outArgumentsCount = 0; if (i != 0) { - var fru = frus[i]; + RegisterUsage.FunctionRegisterUsage fru = frus[i]; inArgumentsCount = fru.InArguments.Length; outArgumentsCount = fru.OutArguments.Length; @@ -325,7 +325,7 @@ namespace Ryujinx.Graphics.Shader.Translation FeatureFlags usedFeatures, byte clipDistancesWritten) { - var sInfo = StructuredProgram.MakeStructuredProgram( + StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram( funcs, attributeUsage, definitions, @@ -340,7 +340,7 @@ namespace Ryujinx.Graphics.Shader.Translation _ => 1 }; - var info = new ShaderProgramInfo( + ShaderProgramInfo info = new( resourceManager.GetConstantBufferDescriptors(), resourceManager.GetStorageBufferDescriptors(), resourceManager.GetTextureDescriptors(), @@ -356,7 +356,7 @@ namespace Ryujinx.Graphics.Shader.Translation clipDistancesWritten, originalDefinitions.OmapTargets); - var hostCapabilities = new HostCapabilities( + HostCapabilities hostCapabilities = new( GpuAccessor.QueryHostReducedPrecision(), GpuAccessor.QueryHostSupportsFragmentShaderInterlock(), GpuAccessor.QueryHostSupportsFragmentShaderOrderingIntel(), @@ -369,7 +369,7 @@ namespace Ryujinx.Graphics.Shader.Translation GpuAccessor.QueryHostSupportsViewportMask(), GpuAccessor.QueryStorageImageExtendedFormats()); - var parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi); + CodeGenParameters parameters = new(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi); return Options.TargetLanguage switch { @@ -485,10 +485,10 @@ namespace Ryujinx.Graphics.Shader.Translation public ShaderProgram GenerateVertexPassthroughForCompute() { - var attributeUsage = new AttributeUsage(GpuAccessor); - var resourceManager = new ResourceManager(ShaderStage.Vertex, GpuAccessor); + AttributeUsage attributeUsage = new(GpuAccessor); + ResourceManager resourceManager = new(ShaderStage.Vertex, GpuAccessor); - var reservations = GetResourceReservations(); + ResourceReservations reservations = GetResourceReservations(); int vertexInfoCbBinding = reservations.VertexInfoConstantBufferBinding; @@ -506,7 +506,7 @@ namespace Ryujinx.Graphics.Shader.Translation BufferDefinition vertexOutputBuffer = new(BufferLayout.Std430, 1, vertexDataSbBinding, "vb_input", vertexInputStruct); resourceManager.Properties.AddOrUpdateStorageBuffer(vertexOutputBuffer); - var context = new EmitterContext(); + EmitterContext context = new(); Operand vertexIndex = Options.TargetApi == TargetApi.OpenGL ? context.Load(StorageKind.Input, IoVariable.VertexId) @@ -551,13 +551,13 @@ namespace Ryujinx.Graphics.Shader.Translation } } - var operations = context.GetOperations(); - var cfg = ControlFlowGraph.Create(operations); - var function = new Function(cfg.Blocks, "main", false, 0, 0); + Operation[] operations = context.GetOperations(); + ControlFlowGraph cfg = ControlFlowGraph.Create(operations); + Function function = new(cfg.Blocks, "main", false, 0, 0); - var transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap); + TransformFeedbackOutput[] transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap); - var definitions = new ShaderDefinitions(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs) + ShaderDefinitions definitions = new(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs) { LastInVertexPipeline = true }; @@ -602,10 +602,10 @@ namespace Ryujinx.Graphics.Shader.Translation break; } - var attributeUsage = new AttributeUsage(GpuAccessor); - var resourceManager = new ResourceManager(ShaderStage.Geometry, GpuAccessor); + AttributeUsage attributeUsage = new(GpuAccessor); + ResourceManager resourceManager = new(ShaderStage.Geometry, GpuAccessor); - var context = new EmitterContext(); + EmitterContext context = new(); for (int v = 0; v < maxOutputVertices; v++) { @@ -646,11 +646,11 @@ namespace Ryujinx.Graphics.Shader.Translation context.EndPrimitive(); - var operations = context.GetOperations(); - var cfg = ControlFlowGraph.Create(operations); - var function = new Function(cfg.Blocks, "main", false, 0, 0); + Operation[] operations = context.GetOperations(); + ControlFlowGraph cfg = ControlFlowGraph.Create(operations); + Function function = new(cfg.Blocks, "main", false, 0, 0); - var definitions = new ShaderDefinitions( + ShaderDefinitions definitions = new( ShaderStage.Geometry, GpuAccessor.QueryGraphicsState(), false, diff --git a/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs b/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs index 946b7c995..4154ef83d 100644 --- a/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs +++ b/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Graphics.Texture.Encoders int w = Math.Min(4, width - x); int h = Math.Min(4, height - y); - var dataUint = MemoryMarshal.Cast(data); + ReadOnlySpan dataUint = MemoryMarshal.Cast(data); int baseOffset = y * width + x; diff --git a/src/Ryujinx.Graphics.Vulkan/Auto.cs b/src/Ryujinx.Graphics.Vulkan/Auto.cs index a26041f15..d97d69ad3 100644 --- a/src/Ryujinx.Graphics.Vulkan/Auto.cs +++ b/src/Ryujinx.Graphics.Vulkan/Auto.cs @@ -63,7 +63,7 @@ namespace Ryujinx.Graphics.Vulkan public T GetMirrorable(CommandBufferScoped cbs, ref int offset, int size, out bool mirrored) { - var mirror = _mirrorable.GetMirrorable(cbs, ref offset, size, out mirrored); + Auto mirror = _mirrorable.GetMirrorable(cbs, ref offset, size, out mirrored); mirror._waitable?.AddBufferUse(cbs.CommandBufferIndex, offset, size, false); return mirror.Get(cbs); } diff --git a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs index e4b68fa40..5260c5d8b 100644 --- a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs +++ b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs @@ -110,7 +110,7 @@ namespace Ryujinx.Graphics.Vulkan { lock (_resources) { - foreach (var resource in _resources.Values) + foreach (BackgroundResource resource in _resources.Values) { resource.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs b/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs index a8bb2bde5..f94a89f6c 100644 --- a/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs +++ b/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs @@ -357,7 +357,7 @@ namespace Ryujinx.Graphics.Vulkan { // Generic pipeline memory barriers will work for desktop GPUs. // They do require a few more access flags on the subpass dependency, though. - foreach (var barrier in _imageBarriers) + foreach (BarrierWithStageFlags barrier in _imageBarriers) { _memoryBarriers.Add(new BarrierWithStageFlags( barrier.Flags, @@ -377,7 +377,7 @@ namespace Ryujinx.Graphics.Vulkan { PipelineStageFlags allFlags = PipelineStageFlags.None; - foreach (var barrier in _memoryBarriers) + foreach (BarrierWithStageFlags barrier in _memoryBarriers) { allFlags |= barrier.Flags.Dest; } diff --git a/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs b/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs index 8f39b6dd3..e1f109dd7 100644 --- a/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs +++ b/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs @@ -231,11 +231,11 @@ namespace Ryujinx.Graphics.Vulkan public BitMapStruct Union(BitMapStruct other) { - var result = new BitMapStruct(); + BitMapStruct result = new(); - var masksSpan = _masks.AsSpan(); - var oMasksSpan = other._masks.AsSpan(); - var nMasksSpan = result._masks.AsSpan(); + Span masksSpan = _masks.AsSpan(); + Span oMasksSpan = other._masks.AsSpan(); + Span nMasksSpan = result._masks.AsSpan(); for (int i = 0; i < masksSpan.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs index c081715d5..2df1311ff 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs @@ -117,7 +117,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe Auto CreateView(VkFormat format, int offset, int size, Action invalidateView) { - var bufferViewCreateInfo = new BufferViewCreateInfo + BufferViewCreateInfo bufferViewCreateInfo = new() { SType = StructureType.BufferViewCreateInfo, Buffer = new VkBuffer(_bufferHandle), @@ -126,7 +126,7 @@ namespace Ryujinx.Graphics.Vulkan Range = (uint)size, }; - _gd.Api.CreateBufferView(_device, in bufferViewCreateInfo, null, out var bufferView).ThrowOnError(); + _gd.Api.CreateBufferView(_device, in bufferViewCreateInfo, null, out BufferView* bufferView).ThrowOnError(); return new Auto(new DisposableBufferView(_gd.Api, _device, bufferView), this, _waitable, _buffer); } @@ -187,7 +187,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var key = ToMirrorKey(offset, size); + ulong key = ToMirrorKey(offset, size); if (_mirrors.TryGetValue(key, out StagingBufferReserved reserved)) { @@ -209,14 +209,14 @@ namespace Ryujinx.Graphics.Vulkan // Build data for the new mirror. - var baseData = new Span((void*)(_map + offset), size); - var modData = _pendingData.AsSpan(offset, size); + Span baseData = new((void*)(_map + offset), size); + Span modData = _pendingData.AsSpan(offset, size); StagingBufferReserved? newMirror = _gd.BufferManager.StagingBuffer.TryReserveData(cbs, size); if (newMirror != null) { - var mirror = newMirror.Value; + StagingBufferReserved mirror = newMirror.Value; _pendingDataRanges.FillData(baseData, modData, offset, new Span((void*)(mirror.Buffer._map + mirror.Offset), size)); if (_mirrors.Count == 0) @@ -323,13 +323,13 @@ namespace Ryujinx.Graphics.Vulkan private void UploadPendingData(CommandBufferScoped cbs, int offset, int size) { - var ranges = _pendingDataRanges.FindOverlaps(offset, size); + List ranges = _pendingDataRanges.FindOverlaps(offset, size); if (ranges != null) { _pendingDataRanges.Remove(offset, size); - foreach (var range in ranges) + foreach (BufferMirrorRangeList.Range range in ranges) { int rangeOffset = Math.Max(offset, range.Offset); int rangeSize = Math.Min(offset + size, range.End) - rangeOffset; @@ -370,7 +370,7 @@ namespace Ryujinx.Graphics.Vulkan public BufferHandle GetHandle() { - var handle = _bufferHandle; + ulong handle = _bufferHandle; return Unsafe.As(ref handle); } @@ -407,7 +407,7 @@ namespace Ryujinx.Graphics.Vulkan if (_flushFence != null) { - var fence = _flushFence; + FenceHolder fence = _flushFence; Interlocked.Increment(ref _flushWaiting); // Don't wait in the lock. @@ -485,7 +485,7 @@ namespace Ryujinx.Graphics.Vulkan public bool RemoveOverlappingMirrors(int offset, int size) { List toRemove = null; - foreach (var key in _mirrors.Keys) + foreach (ulong key in _mirrors.Keys) { (int keyOffset, int keySize) = FromMirrorKey(key); if (!(offset + size <= keyOffset || offset >= keyOffset + keySize)) @@ -498,7 +498,7 @@ namespace Ryujinx.Graphics.Vulkan if (toRemove != null) { - foreach (var key in toRemove) + foreach (ulong key in toRemove) { _mirrors.Remove(key); } @@ -610,8 +610,8 @@ namespace Ryujinx.Graphics.Vulkan BufferHolder srcHolder = _gd.BufferManager.Create(_gd, dataSize, baseType: BufferAllocationType.HostMapped); srcHolder.SetDataUnchecked(0, data); - var srcBuffer = srcHolder.GetBuffer(); - var dstBuffer = this.GetBuffer(cbs.Value.CommandBuffer, true); + Auto srcBuffer = srcHolder.GetBuffer(); + Auto dstBuffer = this.GetBuffer(cbs.Value.CommandBuffer, true); Copy(_gd, cbs.Value, srcBuffer, dstBuffer, 0, offset, dataSize); @@ -666,7 +666,7 @@ namespace Ryujinx.Graphics.Vulkan endRenderPass?.Invoke(); - var dstBuffer = GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true).Get(cbs, dstOffset, data.Length, true).Value; + VkBuffer dstBuffer = GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true).Get(cbs, dstOffset, data.Length, true).Value; InsertBufferBarrier( _gd, @@ -713,8 +713,8 @@ namespace Ryujinx.Graphics.Vulkan int size, bool registerSrcUsage = true) { - var srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; - var dstBuffer = dst.Get(cbs, dstOffset, size, true).Value; + VkBuffer srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; + VkBuffer dstBuffer = dst.Get(cbs, dstOffset, size, true).Value; InsertBufferBarrier( gd, @@ -727,7 +727,7 @@ namespace Ryujinx.Graphics.Vulkan dstOffset, size); - var region = new BufferCopy((ulong)srcOffset, (ulong)dstOffset, (ulong)size); + BufferCopy region = new((ulong)srcOffset, (ulong)dstOffset, (ulong)size); gd.Api.CmdCopyBuffer(cbs.CommandBuffer, srcBuffer, dstBuffer, 1, ®ion); @@ -808,9 +808,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new I8ToI16CacheKey(_gd); + I8ToI16CacheKey key = new(_gd); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { holder = _gd.BufferManager.Create(_gd, (size * 2 + 3) & ~3, baseType: BufferAllocationType.DeviceLocal); @@ -832,9 +832,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new AlignedVertexBufferCacheKey(_gd, stride, alignment); + AlignedVertexBufferCacheKey key = new(_gd, stride, alignment); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { int alignedStride = (stride + (alignment - 1)) & -alignment; @@ -858,9 +858,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new TopologyConversionCacheKey(_gd, pattern, indexSize); + TopologyConversionCacheKey key = new(_gd, pattern, indexSize); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { // The destination index size is always I32. diff --git a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs index f1a2428a5..bf89d63dd 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs @@ -96,20 +96,20 @@ namespace Ryujinx.Graphics.Vulkan public unsafe BufferHandle CreateHostImported(VulkanRenderer gd, nint pointer, int size) { - var usage = HostImportedBufferUsageFlags; + BufferUsageFlags usage = HostImportedBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { usage |= BufferUsageFlags.IndirectBufferBit; } - var externalMemoryBuffer = new ExternalMemoryBufferCreateInfo + ExternalMemoryBufferCreateInfo externalMemoryBuffer = new() { SType = StructureType.ExternalMemoryBufferCreateInfo, HandleTypes = ExternalMemoryHandleTypeFlags.HostAllocationBitExt, }; - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new() { SType = StructureType.BufferCreateInfo, Size = (ulong)size, @@ -118,13 +118,13 @@ namespace Ryujinx.Graphics.Vulkan PNext = &externalMemoryBuffer, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer* buffer).ThrowOnError(); (Auto allocation, ulong offset) = gd.HostMemoryAllocator.GetExistingAllocation(pointer, (ulong)size); gd.Api.BindBufferMemory(_device, buffer, allocation.GetUnsafe().Memory, allocation.GetUnsafe().Offset + offset); - var holder = new BufferHolder(gd, _device, buffer, allocation, size, BufferAllocationType.HostMapped, BufferAllocationType.HostMapped, (int)offset); + BufferHolder holder = new BufferHolder(gd, _device, buffer, allocation, size, BufferAllocationType.HostMapped, BufferAllocationType.HostMapped, (int)offset); BufferCount++; @@ -135,7 +135,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe BufferHandle CreateSparse(VulkanRenderer gd, ReadOnlySpan storageBuffers) { - var usage = DefaultBufferUsageFlags; + BufferUsageFlags usage = DefaultBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Vulkan size += (ulong)range.Size; } - var bufferCreateInfo = new BufferCreateInfo() + BufferCreateInfo bufferCreateInfo = new() { SType = StructureType.BufferCreateInfo, Size = size, @@ -158,10 +158,10 @@ namespace Ryujinx.Graphics.Vulkan Flags = BufferCreateFlags.SparseBindingBit | BufferCreateFlags.SparseAliasedBit }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer* buffer).ThrowOnError(); - var memoryBinds = new SparseMemoryBind[storageBuffers.Length]; - var storageAllocations = new Auto[storageBuffers.Length]; + SparseMemoryBind[] memoryBinds = new SparseMemoryBind[storageBuffers.Length]; + Auto[] storageAllocations = new Auto[storageBuffers.Length]; int storageAllocationsCount = 0; ulong dstOffset = 0; @@ -170,9 +170,9 @@ namespace Ryujinx.Graphics.Vulkan { BufferRange range = storageBuffers[index]; - if (TryGetBuffer(range.Handle, out var existingHolder)) + if (TryGetBuffer(range.Handle, out BufferHolder existingHolder)) { - (var memory, var offset) = existingHolder.GetDeviceMemoryAndOffset(); + (DeviceMemory memory, ulong offset) = existingHolder.GetDeviceMemoryAndOffset(); memoryBinds[index] = new SparseMemoryBind() { @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Vulkan gd.Api.QueueBindSparse(gd.Queue, 1, in bindSparseInfo, default).ThrowOnError(); } - var holder = new BufferHolder(gd, _device, buffer, (int)size, storageAllocations); + BufferHolder holder = new BufferHolder(gd, _device, buffer, (int)size, storageAllocations); BufferCount++; @@ -288,14 +288,14 @@ namespace Ryujinx.Graphics.Vulkan public unsafe MemoryRequirements GetHostImportedUsageRequirements(VulkanRenderer gd) { - var usage = HostImportedBufferUsageFlags; + BufferUsageFlags usage = HostImportedBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new() { SType = StructureType.BufferCreateInfo, Size = (ulong)Environment.SystemPageSize, @@ -303,9 +303,9 @@ namespace Ryujinx.Graphics.Vulkan SharingMode = SharingMode.Exclusive, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer* buffer).ThrowOnError(); - gd.Api.GetBufferMemoryRequirements(_device, buffer, out var requirements); + gd.Api.GetBufferMemoryRequirements(_device, buffer, out MemoryRequirements requirements); gd.Api.DestroyBuffer(_device, buffer, null); @@ -320,7 +320,7 @@ namespace Ryujinx.Graphics.Vulkan bool sparseCompatible = false, BufferAllocationType fallbackType = BufferAllocationType.Auto) { - var usage = DefaultBufferUsageFlags; + BufferUsageFlags usage = DefaultBufferUsageFlags; if (forConditionalRendering && gd.Capabilities.SupportsConditionalRendering) { @@ -331,7 +331,7 @@ namespace Ryujinx.Graphics.Vulkan usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new() { SType = StructureType.BufferCreateInfo, Size = (ulong)size, @@ -339,8 +339,8 @@ namespace Ryujinx.Graphics.Vulkan SharingMode = SharingMode.Exclusive, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); - gd.Api.GetBufferMemoryRequirements(_device, buffer, out var requirements); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer* buffer).ThrowOnError(); + gd.Api.GetBufferMemoryRequirements(_device, buffer, out MemoryRequirements requirements); if (sparseCompatible) { @@ -351,7 +351,7 @@ namespace Ryujinx.Graphics.Vulkan do { - var allocateFlags = type switch + MemoryPropertyFlags allocateFlags = type switch { BufferAllocationType.HostMappedNoCache => DefaultBufferMemoryNoCacheFlags, BufferAllocationType.HostMapped => DefaultBufferMemoryFlags, @@ -402,7 +402,7 @@ namespace Ryujinx.Graphics.Vulkan if (buffer.Handle != 0) { - var holder = new BufferHolder(gd, _device, buffer, allocation, size, baseType, resultType); + BufferHolder holder = new(gd, _device, buffer, allocation, size, baseType, resultType); return holder; } @@ -414,7 +414,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto CreateView(BufferHandle handle, VkFormat format, int offset, int size, Action invalidateView) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.CreateView(format, offset, size, invalidateView); } @@ -424,7 +424,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, bool isWrite, bool isSSBO = false) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(commandBuffer, isWrite, isSSBO); } @@ -434,7 +434,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, int offset, int size, bool isWrite) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(commandBuffer, offset, size, isWrite); } @@ -444,7 +444,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBufferI8ToI16(CommandBufferScoped cbs, BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferI8ToI16(cbs, offset, size); } @@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetAlignedVertexBuffer(CommandBufferScoped cbs, BufferHandle handle, int offset, int size, int stride, int alignment) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetAlignedVertexBuffer(cbs, offset, size, stride, alignment); } @@ -464,7 +464,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBufferTopologyConversion(CommandBufferScoped cbs, BufferHandle handle, int offset, int size, IndexBufferPattern pattern, int indexSize) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferTopologyConversion(cbs, offset, size, pattern, indexSize); } @@ -486,14 +486,14 @@ namespace Ryujinx.Graphics.Vulkan { BufferHolder drawCountBufferHolder = null; - if (!TryGetBuffer(indexBuffer.Handle, out var indexBufferHolder) || - !TryGetBuffer(indirectBuffer.Handle, out var indirectBufferHolder) || + if (!TryGetBuffer(indexBuffer.Handle, out BufferHolder indexBufferHolder) || + !TryGetBuffer(indirectBuffer.Handle, out BufferHolder indirectBufferHolder) || (hasDrawCount && !TryGetBuffer(drawCountBuffer.Handle, out drawCountBufferHolder))) { return (null, null); } - var indexBufferKey = new TopologyConversionIndirectCacheKey( + TopologyConversionIndirectCacheKey indexBufferKey = new( gd, pattern, indexSize, @@ -505,16 +505,16 @@ namespace Ryujinx.Graphics.Vulkan indexBuffer.Offset, indexBuffer.Size, indexBufferKey, - out var convertedIndexBuffer); + out BufferHolder convertedIndexBuffer); - var indirectBufferKey = new IndirectDataCacheKey(pattern); + IndirectDataCacheKey indirectBufferKey = new(pattern); bool hasConvertedIndirectBuffer = indirectBufferHolder.TryGetCachedConvertedBuffer( indirectBuffer.Offset, indirectBuffer.Size, indirectBufferKey, - out var convertedIndirectBuffer); + out BufferHolder convertedIndirectBuffer); - var drawCountBufferKey = new DrawCountCacheKey(); + DrawCountCacheKey drawCountBufferKey = new(); bool hasCachedDrawCount = true; if (hasDrawCount) @@ -568,7 +568,7 @@ namespace Ryujinx.Graphics.Vulkan // Any modification of the indirect buffer should invalidate the index buffers that are associated with it, // since we used the indirect data to find the range of the index buffer that is used. - var indexBufferDependency = new Dependency( + Dependency indexBufferDependency = new( indexBufferHolder, indexBuffer.Offset, indexBuffer.Size, @@ -590,7 +590,7 @@ namespace Ryujinx.Graphics.Vulkan // If we have a draw count, any modification of the draw count should invalidate all indirect buffers // where we used it to find the range of indirect data that is actually used. - var indirectBufferDependency = new Dependency( + Dependency indirectBufferDependency = new( indirectBufferHolder, indirectBuffer.Offset, indirectBuffer.Size, @@ -609,7 +609,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, bool isWrite, out int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { size = holder.Size; return holder.GetBuffer(commandBuffer, isWrite); @@ -621,7 +621,7 @@ namespace Ryujinx.Graphics.Vulkan public PinnedSpan GetData(BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetData(offset, size); } @@ -636,7 +636,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetData(BufferHandle handle, int offset, ReadOnlySpan data, CommandBufferScoped? cbs, Action endRenderPass) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.SetData(offset, data, cbs, endRenderPass); } @@ -644,7 +644,7 @@ namespace Ryujinx.Graphics.Vulkan public void Delete(BufferHandle handle) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.Dispose(); _buffers.Remove((int)Unsafe.As(ref handle)); diff --git a/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs b/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs index e6521e4d3..cf5505dd9 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs @@ -38,7 +38,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly bool Remove(int offset, int size) { - var list = _ranges; + List list = _ranges; bool removedAny = false; if (list != null) { @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan int endOffset = offset + size; int startIndex = overlapIndex; - var currentOverlap = list[overlapIndex]; + Range currentOverlap = list[overlapIndex]; // Orphan the start of the overlap. if (currentOverlap.Offset < offset) @@ -102,7 +102,7 @@ namespace Ryujinx.Graphics.Vulkan public void Add(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list != null) { int overlapIndex = BinarySearch(list, offset, size); @@ -118,8 +118,8 @@ namespace Ryujinx.Graphics.Vulkan while (overlapIndex < list.Count && list[overlapIndex].OverlapsWith(offset, size)) { - var currentOverlap = list[overlapIndex]; - var currentOverlapEndOffset = currentOverlap.Offset + currentOverlap.Size; + Range currentOverlap = list[overlapIndex]; + int currentOverlapEndOffset = currentOverlap.Offset + currentOverlap.Size; if (offset > currentOverlap.Offset) { @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly bool OverlapsWith(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list == null) { return false; @@ -167,7 +167,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly List FindOverlaps(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list == null) { return null; @@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Vulkan int middle = left + (range >> 1); - var item = list[middle]; + Range item = list[middle]; if (item.OverlapsWith(offset, size)) { @@ -230,7 +230,7 @@ namespace Ryujinx.Graphics.Vulkan int size = baseData.Length; int endOffset = offset + size; - var list = _ranges; + List list = _ranges; if (list == null) { baseData.CopyTo(result); @@ -244,7 +244,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < list.Count; i++) { - var range = list[i]; + Range range = list[i]; int rangeEnd = range.Offset + range.Size; diff --git a/src/Ryujinx.Graphics.Vulkan/BufferState.cs b/src/Ryujinx.Graphics.Vulkan/BufferState.cs index e49df765d..bc7c847f1 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferState.cs @@ -1,4 +1,5 @@ using System; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { @@ -23,7 +24,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_buffer != null) { - var buffer = _buffer.Get(cbs, _offset, _size, true).Value; + Buffer buffer = _buffer.Get(cbs, _offset, _size, true).Value; ulong offset = (ulong)_offset; ulong size = (ulong)_size; diff --git a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs index a5e8835a1..311cc2397 100644 --- a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs +++ b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Graphics.Vulkan public void Initialize(Vk api, Device device, CommandPool pool) { - var allocateInfo = new CommandBufferAllocateInfo + CommandBufferAllocateInfo allocateInfo = new() { SType = StructureType.CommandBufferAllocateInfo, CommandBufferCount = 1, @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Vulkan _concurrentFenceWaitUnsupported = concurrentFenceWaitUnsupported; _owner = Thread.CurrentThread; - var commandPoolCreateInfo = new CommandPoolCreateInfo + CommandPoolCreateInfo commandPoolCreateInfo = new() { SType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = queueFamilyIndex, @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InConsumption) { @@ -130,7 +130,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse) { @@ -142,7 +142,7 @@ namespace Ryujinx.Graphics.Vulkan public void AddWaitable(int cbIndex, MultiFenceHolder waitable) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (waitable.AddFence(cbIndex, entry.Fence)) { entry.Waitables.Add(waitable); @@ -155,7 +155,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse && waitable.HasFence(i) && @@ -175,7 +175,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse && entry.Fence == fence) { @@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Vulkan { int index = _queuedIndexes[_queuedIndexesPtr]; - ref var entry = ref _commandBuffers[index]; + ref ReservedCommandBuffer entry = ref _commandBuffers[index]; if (wait || !entry.InConsumption || entry.Fence.IsSignaled()) { @@ -240,7 +240,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[cursor]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cursor]; if (!entry.InUse && !entry.InConsumption) { @@ -248,7 +248,7 @@ namespace Ryujinx.Graphics.Vulkan _inUseCount++; - var commandBufferBeginInfo = new CommandBufferBeginInfo + CommandBufferBeginInfo commandBufferBeginInfo = new() { SType = StructureType.CommandBufferBeginInfo, }; @@ -280,7 +280,7 @@ namespace Ryujinx.Graphics.Vulkan { int cbIndex = cbs.CommandBufferIndex; - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; Debug.Assert(entry.InUse); Debug.Assert(entry.CommandBuffer.Handle == cbs.CommandBuffer.Handle); @@ -289,7 +289,7 @@ namespace Ryujinx.Graphics.Vulkan entry.SubmissionCount++; _inUseCount--; - var commandBuffer = entry.CommandBuffer; + CommandBuffer commandBuffer = entry.CommandBuffer; _api.EndCommandBuffer(commandBuffer).ThrowOnError(); @@ -324,7 +324,7 @@ namespace Ryujinx.Graphics.Vulkan private void WaitAndDecrementRef(int cbIndex, bool refreshFence = true) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (entry.InConsumption) { @@ -332,12 +332,12 @@ namespace Ryujinx.Graphics.Vulkan entry.InConsumption = false; } - foreach (var dependant in entry.Dependants) + foreach (IAuto dependant in entry.Dependants) { dependant.DecrementReferenceCount(cbIndex); } - foreach (var waitable in entry.Waitables) + foreach (MultiFenceHolder waitable in entry.Waitables) { waitable.RemoveFence(cbIndex); waitable.RemoveBufferUses(cbIndex); diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs index 40fc01b24..a39a8d9a2 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Vulkan { if (bufferInfo.Buffer.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorBufferInfo* pBufferInfo = bufferInfo) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -74,7 +74,7 @@ namespace Ryujinx.Graphics.Vulkan { if (imageInfo.ImageView.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorImageInfo* pImageInfo = imageInfo) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Vulkan count++; } - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan { if (texelBufferView.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Vulkan count++; } - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new() { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs index 97669942c..04a36a3ba 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs @@ -24,14 +24,14 @@ namespace Ryujinx.Graphics.Vulkan Api = api; Device = device; - foreach (var poolSize in poolSizes) + foreach (DescriptorPoolSize poolSize in poolSizes) { _freeDescriptors += (int)poolSize.DescriptorCount; } fixed (DescriptorPoolSize* pPoolsSize = poolSizes) { - var descriptorPoolCreateInfo = new DescriptorPoolCreateInfo + DescriptorPoolCreateInfo descriptorPoolCreateInfo = new() { SType = StructureType.DescriptorPoolCreateInfo, Flags = updateAfterBind ? DescriptorPoolCreateFlags.UpdateAfterBindBit : DescriptorPoolCreateFlags.None, @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe DescriptorSetCollection AllocateDescriptorSets(ReadOnlySpan layouts, int consumedDescriptors) { - TryAllocateDescriptorSets(layouts, consumedDescriptors, isTry: false, out var dsc); + TryAllocateDescriptorSets(layouts, consumedDescriptors, isTry: false, out DescriptorSetCollection dsc); return dsc; } @@ -69,7 +69,7 @@ namespace Ryujinx.Graphics.Vulkan { fixed (DescriptorSetLayout* pLayouts = layouts) { - var descriptorSetAllocateInfo = new DescriptorSetAllocateInfo + DescriptorSetAllocateInfo descriptorSetAllocateInfo = new() { SType = StructureType.DescriptorSetAllocateInfo, DescriptorPool = _pool, @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Vulkan PSetLayouts = pLayouts, }; - var result = Api.AllocateDescriptorSets(Device, &descriptorSetAllocateInfo, pDescriptorSets); + Result result = Api.AllocateDescriptorSets(Device, &descriptorSetAllocateInfo, pDescriptorSets); if (isTry && result == Result.ErrorOutOfPoolMemory) { _totalSets = (int)MaxSets; @@ -182,8 +182,8 @@ namespace Ryujinx.Graphics.Vulkan { // If we fail the first time, just create a new pool and try again. - var pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); - if (!pool.TryAllocateDescriptorSets(layouts, consumedDescriptors, out var dsc)) + DescriptorPoolHolder pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); + if (!pool.TryAllocateDescriptorSets(layouts, consumedDescriptors, out DescriptorSetCollection dsc)) { pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); dsc = pool.AllocateDescriptorSets(layouts, consumedDescriptors); diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs index 27a4a2fdd..3b70a841a 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs @@ -86,7 +86,7 @@ namespace Ryujinx.Graphics.Vulkan Size = (int)structureOffset; - var info = new DescriptorUpdateTemplateCreateInfo() + DescriptorUpdateTemplateCreateInfo info = new() { SType = StructureType.DescriptorUpdateTemplateCreateInfo, DescriptorUpdateEntryCount = (uint)segments.Length, @@ -173,7 +173,7 @@ namespace Ryujinx.Graphics.Vulkan Size = (int)structureOffset; - var info = new DescriptorUpdateTemplateCreateInfo() + DescriptorUpdateTemplateCreateInfo info = new() { SType = StructureType.DescriptorUpdateTemplateCreateInfo, DescriptorUpdateEntryCount = (uint)entry, diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs index be63b802c..27b797e77 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; using Format = Ryujinx.Graphics.GAL.Format; using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; @@ -155,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan _uniformSetPd = new int[Constants.MaxUniformBufferBindings]; - var initialImageInfo = new DescriptorImageInfo + DescriptorImageInfo initialImageInfo = new() { ImageLayout = ImageLayout.General, }; @@ -300,13 +301,13 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < segment.Count; i++) { - ref var texture = ref _textureRefs[segment.Binding + i]; + ref TextureRef texture = ref _textureRefs[segment.Binding + i]; texture.View?.PrepareForUsage(cbs, texture.Stage.ConvertToPipelineStageFlags(), FeedbackLoopHazards); } } else { - ref var arrayRef = ref _textureArrayRefs[segment.Binding]; + ref ArrayRef arrayRef = ref _textureArrayRefs[segment.Binding]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -321,13 +322,13 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < segment.Count; i++) { - ref var image = ref _imageRefs[segment.Binding + i]; + ref ImageRef image = ref _imageRefs[segment.Binding + i]; image.View?.PrepareForUsage(cbs, image.Stage.ConvertToPipelineStageFlags(), FeedbackLoopHazards); } } else { - ref var arrayRef = ref _imageArrayRefs[segment.Binding]; + ref ArrayRef arrayRef = ref _imageArrayRefs[segment.Binding]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -336,7 +337,7 @@ namespace Ryujinx.Graphics.Vulkan for (int setIndex = PipelineBase.DescriptorSetLayouts; setIndex < _program.BindingSegments.Length; setIndex++) { - var bindingSegments = _program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = _program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -352,13 +353,13 @@ namespace Ryujinx.Graphics.Vulkan or ResourceType.TextureAndSampler or ResourceType.BufferTexture) { - ref var arrayRef = ref _textureArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; + ref ArrayRef arrayRef = ref _textureArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } else if (segment.Type is ResourceType.Image or ResourceType.BufferImage) { - ref var arrayRef = ref _imageArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; + ref ArrayRef arrayRef = ref _imageArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -423,8 +424,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var assignment = buffers[i]; - var buffer = assignment.Range; + BufferAssignment assignment = buffers[i]; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto vkBuffer = buffer.Handle == BufferHandle.Null @@ -439,7 +440,7 @@ namespace Ryujinx.Graphics.Vulkan Range = (ulong)buffer.Size, }; - var newRef = new BufferRef(vkBuffer, ref buffer); + BufferRef newRef = new(vkBuffer, ref buffer); ref DescriptorBufferInfo currentInfo = ref _storageBuffers[index]; @@ -459,7 +460,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var vkBuffer = buffers[i]; + Auto vkBuffer = buffers[i]; int index = first + i; ref BufferRef currentBufferRef = ref _storageBufferRefs[index]; @@ -632,8 +633,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var assignment = buffers[i]; - var buffer = assignment.Range; + BufferAssignment assignment = buffers[i]; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto vkBuffer = buffer.Handle == BufferHandle.Null @@ -677,7 +678,7 @@ namespace Ryujinx.Graphics.Vulkan return; } - var program = _program; + ShaderCollection program = _program; if ((_dirty & DirtyFlags.Uniform) == DirtyFlags.Uniform) { @@ -759,14 +760,14 @@ namespace Ryujinx.Graphics.Vulkan [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateAndBind(CommandBufferScoped cbs, ShaderCollection program, int setIndex, PipelineBindPoint pbp) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { return; } - var dummyBuffer = _dummyBuffer?.GetBuffer(); + Auto dummyBuffer = _dummyBuffer?.GetBuffer(); if (_updateDescriptorCacheCbIndex) { @@ -774,7 +775,7 @@ namespace Ryujinx.Graphics.Vulkan program.UpdateDescriptorCacheCommandBufferIndex(cbs.CommandBufferIndex); } - var dsc = program.GetNewDescriptorSetCollection(setIndex, out var isNew).Get(cbs); + DescriptorSetCollection dsc = program.GetNewDescriptorSetCollection(setIndex, out bool isNew).Get(cbs); if (!program.HasMinimalLayout) { @@ -823,7 +824,7 @@ namespace Ryujinx.Graphics.Vulkan if (_storageSet.Set(index)) { - ref var info = ref _storageBuffers[index]; + ref DescriptorBufferInfo info = ref _storageBuffers[index]; bool mirrored = UpdateBuffer(cbs, ref info, @@ -849,8 +850,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[binding + i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[binding + i]; texture.ImageView = refs.ImageView?.Get(cbs).Value ?? default; texture.Sampler = refs.Sampler?.Get(cbs).Value ?? default; @@ -933,7 +934,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var sets = dsc.GetSets(); + DescriptorSet[] sets = dsc.GetSets(); _templateUpdater.Commit(_gd, _device, sets[0]); _gd.Api.CmdBindDescriptorSets(cbs.CommandBuffer, pbp, _program.PipelineLayout, (uint)setIndex, 1, sets, 0, ReadOnlySpan.Empty); @@ -942,7 +943,7 @@ namespace Ryujinx.Graphics.Vulkan private void UpdateAndBindTexturesWithoutTemplate(CommandBufferScoped cbs, ShaderCollection program, PipelineBindPoint pbp) { int setIndex = PipelineBase.TextureSetIndex; - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -955,7 +956,7 @@ namespace Ryujinx.Graphics.Vulkan program.UpdateDescriptorCacheCommandBufferIndex(cbs.CommandBufferIndex); } - var dsc = program.GetNewDescriptorSetCollection(setIndex, out _).Get(cbs); + DescriptorSetCollection dsc = program.GetNewDescriptorSetCollection(setIndex, out _).Get(cbs); foreach (ResourceBindingSegment segment in bindingSegments) { @@ -970,8 +971,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[binding + i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[binding + i]; texture.ImageView = refs.ImageView?.Get(cbs).Value ?? default; texture.Sampler = refs.Sampler?.Get(cbs).Value ?? default; @@ -1014,7 +1015,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var sets = dsc.GetSets(); + DescriptorSet[] sets = dsc.GetSets(); _gd.Api.CmdBindDescriptorSets(cbs.CommandBuffer, pbp, _program.PipelineLayout, (uint)setIndex, 1, sets, 0, ReadOnlySpan.Empty); } @@ -1023,8 +1024,8 @@ namespace Ryujinx.Graphics.Vulkan private void UpdateAndBindUniformBufferPd(CommandBufferScoped cbs) { int sequence = _pdSequence; - var bindingSegments = _program.BindingSegments[PipelineBase.UniformSetIndex]; - var dummyBuffer = _dummyBuffer?.GetBuffer(); + ResourceBindingSegment[] bindingSegments = _program.BindingSegments[PipelineBase.UniformSetIndex]; + Auto dummyBuffer = _dummyBuffer?.GetBuffer(); long updatedBindings = 0; DescriptorSetTemplateWriter writer = _templateUpdater.Begin(32 * Unsafe.SizeOf()); @@ -1076,7 +1077,7 @@ namespace Ryujinx.Graphics.Vulkan return; } - var dummyBuffer = _dummyBuffer?.GetBuffer().Get(cbs).Value ?? default; + Buffer dummyBuffer = _dummyBuffer?.GetBuffer().Get(cbs).Value ?? default; foreach (ResourceBindingSegment segment in _program.ClearSegments[setIndex]) { @@ -1088,7 +1089,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int setIndex = PipelineBase.DescriptorSetLayouts; setIndex < program.BindingSegments.Length; setIndex++) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs index 1d2b4c6ea..b8992c652 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs @@ -41,9 +41,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/AreaScaling.spv"); + byte[] scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/AreaScaling.spv"); - var scalingResourceLayout = new ResourceLayoutBuilder() + ResourceLayout scalingResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -82,7 +82,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects ]; int rangeSize = dimensionsBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, dimensionsBuffer); int threadGroupWorkRegionDim = 16; diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs index 360f33778..04e3c383c 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs @@ -53,15 +53,15 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrScaling.spv"); - var sharpeningShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrSharpening.spv"); + byte[] scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrScaling.spv"); + byte[] sharpeningShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrSharpening.spv"); - var scalingResourceLayout = new ResourceLayoutBuilder() + ResourceLayout scalingResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var sharpeningResourceLayout = new ResourceLayoutBuilder() + ResourceLayout sharpeningResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 3) .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 4) @@ -94,9 +94,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects || _intermediaryTexture.Info.Height != height || !_intermediaryTexture.Info.Equals(view.Info)) { - var originalInfo = view.Info; + TextureCreateInfo originalInfo = view.Info; - var info = new TextureCreateInfo( + TextureCreateInfo info = new( width, height, originalInfo.Depth, @@ -140,11 +140,11 @@ namespace Ryujinx.Graphics.Vulkan.Effects ]; int rangeSize = dimensionsBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, dimensionsBuffer); ReadOnlySpan sharpeningBufferData = [1.5f - (Level * 0.01f * 1.5f)]; - using var sharpeningBuffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, sizeof(float)); + using ScopedTemporaryBuffer sharpeningBuffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, sizeof(float)); sharpeningBuffer.Holder.SetDataUnchecked(sharpeningBuffer.Offset, sharpeningBufferData); int threadGroupWorkRegionDim = 16; diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs index fff05b121..8f7a6846b 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs @@ -37,9 +37,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects { _pipeline.Initialize(); - var shader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/Fxaa.spv"); + byte[] shader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/Fxaa.spv"); - var resourceLayout = new ResourceLayoutBuilder() + ResourceLayout resourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -65,14 +65,14 @@ namespace Ryujinx.Graphics.Vulkan.Effects ReadOnlySpan resolutionBuffer = [view.Width, view.Height]; int rangeSize = resolutionBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, resolutionBuffer); _pipeline.SetUniformBuffers([new BufferAssignment(2, buffer.Range)]); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); _pipeline.SetImage(ShaderStage.Compute, 0, _texture?.GetView(FormatTable.ConvertRgba8SrgbToUnorm(view.Info.Format))); _pipeline.DispatchCompute(dispatchX, dispatchY, 1); diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs index 29d2edf19..6791e590b 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs @@ -1,4 +1,5 @@ using Ryujinx.Common; +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; @@ -74,23 +75,23 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var edgeShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaEdge.spv"); - var blendShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaBlend.spv"); - var neighbourShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaNeighbour.spv"); + byte[] edgeShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaEdge.spv"); + byte[] blendShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaBlend.spv"); + byte[] neighbourShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaNeighbour.spv"); - var edgeResourceLayout = new ResourceLayoutBuilder() + ResourceLayout edgeResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var blendResourceLayout = new ResourceLayoutBuilder() + ResourceLayout blendResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 3) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 4) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var neighbourResourceLayout = new ResourceLayoutBuilder() + ResourceLayout neighbourResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 3) @@ -108,7 +109,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects QualityUltra = Quality == 3 ? 1 : 0, }; - var specInfo = new SpecDescription( + SpecDescription specInfo = new( (0, SpecConstType.Int32), (1, SpecConstType.Int32), (2, SpecConstType.Int32), @@ -139,7 +140,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects private void Initialize() { - var areaInfo = new TextureCreateInfo(AreaWidth, + TextureCreateInfo areaInfo = new(AreaWidth, AreaHeight, 1, 1, @@ -155,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects SwizzleComponent.Blue, SwizzleComponent.Alpha); - var searchInfo = new TextureCreateInfo(SearchWidth, + TextureCreateInfo searchInfo = new(SearchWidth, SearchHeight, 1, 1, @@ -171,8 +172,8 @@ namespace Ryujinx.Graphics.Vulkan.Effects SwizzleComponent.Blue, SwizzleComponent.Alpha); - var areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaAreaTexture.bin"); - var searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaSearchTexture.bin"); + MemoryOwner areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaAreaTexture.bin"); + MemoryOwner searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaSearchTexture.bin"); _areaTexture = _renderer.CreateTexture(areaInfo) as TextureView; _searchTexture = _renderer.CreateTexture(searchInfo) as TextureView; @@ -202,8 +203,8 @@ namespace Ryujinx.Graphics.Vulkan.Effects _renderer.Pipeline.TextureBarrier(); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); // Edge pass _pipeline.SetProgram(_edgeProgram); @@ -212,7 +213,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects ReadOnlySpan resolutionBuffer = [view.Width, view.Height]; int rangeSize = resolutionBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, resolutionBuffer); _pipeline.SetUniformBuffers([new BufferAssignment(2, buffer.Range)]); diff --git a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs index a20affcf8..63737f355 100644 --- a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Vulkan _device = device; _concurrentWaitUnsupported = concurrentWaitUnsupported; - var fenceCreateInfo = new FenceCreateInfo + FenceCreateInfo fenceCreateInfo = new() { SType = StructureType.FenceCreateInfo, }; diff --git a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs index 4f7244c8a..b5ed12158 100644 --- a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs +++ b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs @@ -98,11 +98,11 @@ namespace Ryujinx.Graphics.Vulkan public bool BufferFormatSupports(FormatFeatureFlags flags, Format format) { - var formatFeatureFlags = _bufferTable[(int)format]; + FormatFeatureFlags formatFeatureFlags = _bufferTable[(int)format]; if (formatFeatureFlags == 0) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out FormatProperties fp); formatFeatureFlags = fp.BufferFeatures; _bufferTable[(int)format] = formatFeatureFlags; } @@ -131,18 +131,18 @@ namespace Ryujinx.Graphics.Vulkan public bool BufferFormatSupports(FormatFeatureFlags flags, VkFormat format) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, format, out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, format, out FormatProperties fp); return (fp.BufferFeatures & flags) == flags; } public bool OptimalFormatSupports(FormatFeatureFlags flags, Format format) { - var formatFeatureFlags = _optimalTable[(int)format]; + FormatFeatureFlags formatFeatureFlags = _optimalTable[(int)format]; if (formatFeatureFlags == 0) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out FormatProperties fp); formatFeatureFlags = fp.OptimalTilingFeatures; _optimalTable[(int)format] = formatFeatureFlags; } @@ -152,7 +152,7 @@ namespace Ryujinx.Graphics.Vulkan public VkFormat ConvertToVkFormat(Format srcFormat, bool storageFeatureFlagRequired) { - var format = FormatTable.GetFormat(srcFormat); + VkFormat format = FormatTable.GetFormat(srcFormat); var requiredFeatures = FormatFeatureFlags.SampledImageBit | FormatFeatureFlags.TransferSrcBit | @@ -194,7 +194,7 @@ namespace Ryujinx.Graphics.Vulkan public VkFormat ConvertToVertexVkFormat(Format srcFormat) { - var format = FormatTable.GetFormat(srcFormat); + VkFormat format = FormatTable.GetFormat(srcFormat); if (!BufferFormatSupports(FormatFeatureFlags.VertexBufferBit, srcFormat) || (IsRGB16IntFloat(srcFormat) && VulkanConfiguration.ForceRGB16IntFloatUnsupported)) diff --git a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs index df4edc9df..0b6abb5b3 100644 --- a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs +++ b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Graphics.Vulkan public FramebufferParams(Device device, TextureView view, uint width, uint height) { - var format = view.Info.Format; + Format format = view.Info.Format; bool isDepthStencil = format.IsDepthOrStencil(); @@ -112,7 +112,7 @@ namespace Ryujinx.Graphics.Vulkan { if (IsValidTextureView(color)) { - var texture = (TextureView)color; + TextureView texture = (TextureView)color; _attachments[index] = texture.GetImageViewForAttachment(); _colors[index] = texture; @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Vulkan AttachmentFormats[index] = texture.VkFormat; AttachmentIndices[index] = bindIndex; - var format = texture.Info.Format; + Format format = texture.Info.Format; if (format.IsInteger()) { @@ -348,7 +348,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_colors != null && (uint)index < ColorAttachmentsCount) { - var format = _colors[index].Info.Format; + Format format = _colors[index].Info.Format; if (format.IsSint()) { @@ -403,7 +403,7 @@ namespace Ryujinx.Graphics.Vulkan attachments[i] = _attachments[i].Get(cbs).Value; } - var framebufferCreateInfo = new FramebufferCreateInfo + FramebufferCreateInfo framebufferCreateInfo = new() { SType = StructureType.FramebufferCreateInfo, RenderPass = renderPass.Get(cbs).Value, @@ -414,13 +414,13 @@ namespace Ryujinx.Graphics.Vulkan Layers = Layers, }; - api.CreateFramebuffer(_device, in framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); + api.CreateFramebuffer(_device, in framebufferCreateInfo, null, out Framebuffer* framebuffer).ThrowOnError(); return new Auto(new DisposableFramebuffer(api, _device, framebuffer), null, _attachments[..AttachmentsCount]); } public TextureView[] GetAttachmentViews() { - var result = new TextureView[AttachmentsCount]; + TextureView[] result = new TextureView[AttachmentsCount]; _colors?.AsSpan(..ColorAttachmentsCount).CopyTo(result.AsSpan()); if (_depthStencil != null) diff --git a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs index 611b7abdd..c811907e5 100644 --- a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs +++ b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan public void Add(ref TKey key, TValue value) { - var entry = new Entry + Entry entry = new() { Hash = key.GetHashCode(), Key = key, @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Vulkan int hashCode = key.GetHashCode(); int bucketIndex = hashCode & TotalBucketsMask; - ref var bucket = ref _hashTable[bucketIndex]; + ref Bucket bucket = ref _hashTable[bucketIndex]; if (bucket.Entries != null) { int index = bucket.Length; @@ -102,11 +102,11 @@ namespace Ryujinx.Graphics.Vulkan { int hashCode = key.GetHashCode(); - ref var bucket = ref _hashTable[hashCode & TotalBucketsMask]; - var entries = bucket.AsSpan(); + ref Bucket bucket = ref _hashTable[hashCode & TotalBucketsMask]; + Span entries = bucket.AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { @@ -124,10 +124,10 @@ namespace Ryujinx.Graphics.Vulkan { int hashCode = key.GetHashCode(); - var entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); + Span entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { diff --git a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs index 88e6e39ea..712a5a1f1 100644 --- a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs +++ b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs @@ -5,6 +5,7 @@ using Ryujinx.Graphics.Shader.Translation; using Silk.NET.Vulkan; using System; using System.Numerics; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; using Format = Ryujinx.Graphics.GAL.Format; using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; @@ -63,7 +64,7 @@ namespace Ryujinx.Graphics.Vulkan _samplerLinear = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); _samplerNearest = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Nearest, MagFilter.Nearest)); - var blitResourceLayout = new ResourceLayoutBuilder() + ResourceLayout blitResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1) .Add(ResourceStages.Fragment, ResourceType.TextureAndSampler, 0).Build(); @@ -82,7 +83,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorBlitClearAlphaFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv) ], blitResourceLayout); - var colorClearResourceLayout = new ResourceLayoutBuilder().Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1).Build(); + ResourceLayout colorClearResourceLayout = new ResourceLayoutBuilder().Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1).Build(); _programColorClearF = gd.CreateProgramWithMinimalLayout([ new ShaderSource(ReadSpirv("ColorClearVertex.spv"), ShaderStage.Vertex, TargetLanguage.Spirv), @@ -104,7 +105,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("DepthStencilClearFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv) ], colorClearResourceLayout); - var strideChangeResourceLayout = new ResourceLayoutBuilder() + ResourceLayout strideChangeResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -113,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ChangeBufferStride.spv"), ShaderStage.Compute, TargetLanguage.Spirv) ], strideChangeResourceLayout); - var colorCopyResourceLayout = new ResourceLayoutBuilder() + ResourceLayout colorCopyResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 0) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -130,7 +131,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorCopyWideningCompute.spv"), ShaderStage.Compute, TargetLanguage.Spirv) ], colorCopyResourceLayout); - var colorDrawToMsResourceLayout = new ResourceLayoutBuilder() + ResourceLayout colorDrawToMsResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Fragment, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Fragment, ResourceType.TextureAndSampler, 0).Build(); @@ -139,7 +140,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorDrawToMsFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv) ], colorDrawToMsResourceLayout); - var convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -148,7 +149,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ConvertD32S8ToD24S8.spv"), ShaderStage.Compute, TargetLanguage.Spirv) ], convertD32S8ToD24S8ResourceLayout); - var convertIndexBufferResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertIndexBufferResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -157,7 +158,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ConvertIndexBuffer.spv"), ShaderStage.Compute, TargetLanguage.Spirv) ], convertIndexBufferResourceLayout); - var convertIndirectDataResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertIndirectDataResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true) @@ -230,17 +231,17 @@ namespace Ryujinx.Graphics.Vulkan { gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); for (int l = 0; l < levels; l++) { - var mipSrcRegion = new Extents2D( + Extents2D mipSrcRegion = new( srcRegion.X1 >> l, srcRegion.Y1 >> l, srcRegion.X2 >> l, srcRegion.Y2 >> l); - var mipDstRegion = new Extents2D( + Extents2D mipDstRegion = new( dstRegion.X1 >> l, dstRegion.Y1 >> l, dstRegion.X2 >> l, @@ -248,8 +249,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < layers; z++) { - var srcView = Create2DLayerView(src, z, l); - var dstView = Create2DLayerView(dst, z, l); + TextureView srcView = Create2DLayerView(src, z, l); + TextureView dstView = Create2DLayerView(dst, z, l); if (isDepthOrStencil) { @@ -310,7 +311,7 @@ namespace Ryujinx.Graphics.Vulkan int dstWidth = Math.Max(1, dst.Width >> mipDstLevel); int dstHeight = Math.Max(1, dst.Height >> mipDstLevel); - var extents = new Extents2D( + Extents2D extents = new( 0, 0, Math.Min(srcWidth, dstWidth), @@ -318,8 +319,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, mipSrcLevel); - var dstView = Create2DLayerView(dst, dstLayer + z, mipDstLevel); + TextureView srcView = Create2DLayerView(src, srcLayer + z, mipSrcLevel); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, mipDstLevel); BlitColor( gd, @@ -357,7 +358,7 @@ namespace Ryujinx.Graphics.Vulkan const int RegionBufferSize = 16; - var sampler = linearFilter ? _samplerLinear : _samplerNearest; + ISampler sampler = linearFilter ? _samplerLinear : _samplerNearest; _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Fragment, 0, src, sampler); @@ -378,7 +379,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); @@ -386,7 +387,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -474,7 +475,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); @@ -482,7 +483,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -505,11 +506,11 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetViewports(viewports); _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); if (aspectFlags.HasFlag(ImageAspectFlags.DepthBit)) { - var depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); + TextureView depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); BlitDepthStencilDraw(depthTexture, isDepth: true); @@ -521,7 +522,7 @@ namespace Ryujinx.Graphics.Vulkan if (aspectFlags.HasFlag(ImageAspectFlags.StencilBit) && _programStencilBlit != null) { - var stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); + TextureView stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); BlitDepthStencilDraw(stencilTexture, isDepth: false); @@ -624,11 +625,11 @@ namespace Ryujinx.Graphics.Vulkan gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); _pipeline.SetCommandBuffer(cbs); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, clearColor); @@ -686,11 +687,11 @@ namespace Ryujinx.Graphics.Vulkan gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); _pipeline.SetCommandBuffer(cbs); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, [depthValue]); @@ -747,7 +748,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - var bufferHandle = gd.BufferManager.CreateWithHandle(gd, RegionBufferSize); + BufferHandle bufferHandle = gd.BufferManager.CreateWithHandle(gd, RegionBufferSize); gd.BufferManager.SetData(bufferHandle, 0, region); @@ -755,7 +756,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -790,11 +791,11 @@ namespace Ryujinx.Graphics.Vulkan int elems = size / stride; int newSize = elems * newStride; - var srcBufferAuto = src.GetBuffer(); - var dstBufferAuto = dst.GetBuffer(); + Auto srcBufferAuto = src.GetBuffer(); + Auto dstBufferAuto = dst.GetBuffer(); - var srcBuffer = srcBufferAuto.Get(cbs, srcOffset, size).Value; - var dstBuffer = dstBufferAuto.Get(cbs, 0, newSize).Value; + Buffer srcBuffer = srcBufferAuto.Get(cbs, srcOffset, size).Value; + Buffer dstBuffer = dstBufferAuto.Get(cbs, 0, newSize).Value; var access = supportsUint8 ? AccessFlags.ShaderWriteBit : AccessFlags.TransferWriteBit; var stage = supportsUint8 ? PipelineStageFlags.ComputeShaderBit : PipelineStageFlags.TransferBit; @@ -821,7 +822,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[2] = size; shaderParams[3] = srcOffset; - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -845,7 +846,7 @@ namespace Ryujinx.Graphics.Vulkan { gd.Api.CmdFillBuffer(cbs.CommandBuffer, dstBuffer, 0, Vk.WholeSize, 0); - var bufferCopy = new BufferCopy[elems]; + BufferCopy[] bufferCopy = new BufferCopy[elems]; for (ulong i = 0; i < (ulong)elems; i++) { @@ -885,7 +886,7 @@ namespace Ryujinx.Graphics.Vulkan int convertedCount = pattern.GetConvertedCount(indexCount); int outputIndexSize = 4; - var dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; + Buffer dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; const int ParamsBufferSize = 16 * sizeof(int); @@ -902,8 +903,8 @@ namespace Ryujinx.Graphics.Vulkan pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]); - using var patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); - var patternBuffer = patternScoped.Holder; + using ScopedTemporaryBuffer patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + BufferHolder patternBuffer = patternScoped.Holder; patternBuffer.SetDataUnchecked(patternScoped.Offset, shaderParams); @@ -963,7 +964,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[0] = BitOperations.Log2((uint)ratio); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -990,8 +991,8 @@ namespace Ryujinx.Graphics.Vulkan // - Maximum component size is 4 (R32). int componentSize = Math.Min(Math.Min(srcBpp, dstBpp), 4); - var srcFormat = GetFormat(componentSize, srcBpp / componentSize); - var dstFormat = GetFormat(componentSize, dstBpp / componentSize); + Format srcFormat = GetFormat(componentSize, srcBpp / componentSize); + Format dstFormat = GetFormat(componentSize, dstBpp / componentSize); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); @@ -999,8 +1000,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, srcLevel + l, srcFormat); - var dstView = Create2DLayerView(dst, dstLayer + z, dstLevel + l); + TextureView srcView = Create2DLayerView(src, srcLayer + z, srcLevel + l, srcFormat); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, dstLevel + l); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Compute, 0, srcView, null); _pipeline.SetImage(ShaderStage.Compute, 0, dstView.GetView(dstFormat)); @@ -1047,7 +1048,7 @@ namespace Ryujinx.Graphics.Vulkan int samples = src.Info.Samples; bool isDepthOrStencil = src.Info.Format.IsDepthOrStencil(); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); // X and Y are the expected texture samples. // Z and W are the actual texture samples used. @@ -1055,7 +1056,7 @@ namespace Ryujinx.Graphics.Vulkan (shaderParams[0], shaderParams[1]) = GetSampleCountXYLog2(samples); (shaderParams[2], shaderParams[3]) = GetSampleCountXYLog2((int)TextureStorage.ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)samples)); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -1082,7 +1083,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle(0, 0, dst.Width, dst.Height); + Rectangle rect = new(0, 0, dst.Width, dst.Height); viewports[0] = new Viewport( rect, @@ -1099,8 +1100,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget(dstView, (uint)dst.Width, (uint)dst.Height); @@ -1119,7 +1120,7 @@ namespace Ryujinx.Graphics.Vulkan } else { - var format = GetFormat(src.Info.BytesPerPixel); + Format format = GetFormat(src.Info.BytesPerPixel); int dispatchX = (dst.Info.Width + 31) / 32; int dispatchY = (dst.Info.Height + 31) / 32; @@ -1128,8 +1129,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0, format); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0, format); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Compute, 0, srcView, null); _pipeline.SetImage(ShaderStage.Compute, 0, dstView.GetView(format)); @@ -1173,7 +1174,7 @@ namespace Ryujinx.Graphics.Vulkan int samples = dst.Info.Samples; bool isDepthOrStencil = src.Info.Format.IsDepthOrStencil(); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); // X and Y are the expected texture samples. // Z and W are the actual texture samples used. @@ -1181,7 +1182,7 @@ namespace Ryujinx.Graphics.Vulkan (shaderParams[0], shaderParams[1]) = GetSampleCountXYLog2(samples); (shaderParams[2], shaderParams[3]) = GetSampleCountXYLog2((int)TextureStorage.ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)samples)); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -1203,7 +1204,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle(0, 0, dst.Width, dst.Height); + Rectangle rect = new(0, 0, dst.Width, dst.Height); viewports[0] = new Viewport( rect, @@ -1225,8 +1226,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget(dstView, (uint)dst.Width, (uint)dst.Height); @@ -1247,13 +1248,13 @@ namespace Ryujinx.Graphics.Vulkan { _pipeline.SetProgram(_programColorDrawToMs); - var format = GetFormat(src.Info.BytesPerPixel); - var vkFormat = FormatTable.GetFormat(format); + Format format = GetFormat(src.Info.BytesPerPixel); + VkFormat vkFormat = FormatTable.GetFormat(format); for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0, format); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0, format); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Fragment, 0, srcView, null); _pipeline.SetRenderTarget(dstView.GetView(format), (uint)dst.Width, (uint)dst.Height); @@ -1293,7 +1294,7 @@ namespace Ryujinx.Graphics.Vulkan { if (aspectFlags.HasFlag(ImageAspectFlags.DepthBit)) { - var depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); + TextureView depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); CopyMSAspectDraw(depthTexture, fromMS, isDepth: true); @@ -1305,7 +1306,7 @@ namespace Ryujinx.Graphics.Vulkan if (aspectFlags.HasFlag(ImageAspectFlags.StencilBit) && _programStencilDrawToMs != null) { - var stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); + TextureView stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); CopyMSAspectDraw(stencilTexture, fromMS, isDepth: false); @@ -1385,14 +1386,14 @@ namespace Ryujinx.Graphics.Vulkan return from; } - var target = from.Info.Target switch + Target target = from.Info.Target switch { Target.Texture1DArray => Target.Texture1D, Target.Texture2DMultisampleArray => Target.Texture2DMultisample, _ => Target.Texture2D, }; - var info = new TextureCreateInfo( + TextureCreateInfo info = new( Math.Max(1, from.Info.Width >> level), Math.Max(1, from.Info.Height >> level), 1, @@ -1494,8 +1495,8 @@ namespace Ryujinx.Graphics.Vulkan int convertedCount = pattern.GetConvertedCount(indexCount); int outputIndexSize = 4; - var srcBuffer = srcIndexBuffer.GetBuffer().Get(cbs, srcIndexBufferOffset, indexCount * indexSize).Value; - var dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; + Buffer srcBuffer = srcIndexBuffer.GetBuffer().Get(cbs, srcIndexBufferOffset, indexCount * indexSize).Value; + Buffer dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; const int ParamsBufferSize = 24 * sizeof(int); const int ParamsIndirectDispatchOffset = 16 * sizeof(int); @@ -1522,9 +1523,9 @@ namespace Ryujinx.Graphics.Vulkan pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]); - using var patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); - var patternBuffer = patternScoped.Holder; - var patternBufferAuto = patternBuffer.GetBuffer(); + using ScopedTemporaryBuffer patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + BufferHolder patternBuffer = patternScoped.Holder; + Auto patternBufferAuto = patternBuffer.GetBuffer(); patternBuffer.SetDataUnchecked(patternScoped.Offset, shaderParams); @@ -1596,10 +1597,10 @@ namespace Ryujinx.Graphics.Vulkan int inSize = pixelCount * 2 * sizeof(int); int outSize = pixelCount * sizeof(int); - var srcBufferAuto = src.GetBuffer(); + Auto srcBufferAuto = src.GetBuffer(); - var srcBuffer = srcBufferAuto.Get(cbs, 0, inSize).Value; - var dstBuffer = dstBufferAuto.Get(cbs, dstOffset, outSize).Value; + Buffer srcBuffer = srcBufferAuto.Get(cbs, 0, inSize).Value; + Buffer dstBuffer = dstBufferAuto.Get(cbs, dstOffset, outSize).Value; var access = AccessFlags.ShaderWriteBit; var stage = PipelineStageFlags.ComputeShaderBit; @@ -1633,7 +1634,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[0] = pixelCount; shaderParams[1] = dstOffset; - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); diff --git a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs index 69bf69919..2f5a343c5 100644 --- a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_lock) { // Does a compatible allocation exist in the tree? - var allocations = new HostMemoryAllocation[10]; + HostMemoryAllocation[] allocations = new HostMemoryAllocation[10]; ulong start = (ulong)pointer; ulong end = start + size; @@ -115,7 +115,7 @@ namespace Ryujinx.Graphics.Vulkan PNext = &importInfo, }; - var memoryAllocateInfo = new MemoryAllocateInfo + MemoryAllocateInfo memoryAllocateInfo = new() { SType = StructureType.MemoryAllocateInfo, AllocationSize = pageAlignedSize, @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Vulkan PNext = &priorityInfo, }; - Result result = _api.AllocateMemory(_device, in memoryAllocateInfo, null, out var deviceMemory); + Result result = _api.AllocateMemory(_device, in memoryAllocateInfo, null, out DeviceMemory* deviceMemory); if (result < Result.Success) { @@ -131,9 +131,9 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var allocation = new MemoryAllocation(this, deviceMemory, pageAlignedPointer, 0, pageAlignedSize); - var allocAuto = new Auto(allocation); - var hostAlloc = new HostMemoryAllocation(allocAuto, pageAlignedPointer, pageAlignedSize); + MemoryAllocation allocation = new MemoryAllocation(this, deviceMemory, pageAlignedPointer, 0, pageAlignedSize); + Auto allocAuto = new(allocation); + HostMemoryAllocation hostAlloc = new(allocAuto, pageAlignedPointer, pageAlignedSize); allocAuto.IncrementReferenceCount(); allocAuto.Dispose(); // Kept alive by ref count only. @@ -152,7 +152,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_lock) { // Does a compatible allocation exist in the tree? - var allocations = new HostMemoryAllocation[10]; + HostMemoryAllocation[] allocations = new HostMemoryAllocation[10]; ulong start = (ulong)pointer; ulong end = start + size; diff --git a/src/Ryujinx.Graphics.Vulkan/ImageArray.cs b/src/Ryujinx.Graphics.Vulkan/ImageArray.cs index 959a12849..47c180696 100644 --- a/src/Ryujinx.Graphics.Vulkan/ImageArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/ImageArray.cs @@ -128,8 +128,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < textures.Length; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[i]; if (i > 0 && _textureRefs[i - 1].View == refs.View) { diff --git a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs index d26fea307..88976e8bb 100644 --- a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs @@ -115,7 +115,7 @@ namespace Ryujinx.Graphics.Vulkan // Convert the index buffer using the given pattern. int indexSize = GetIndexSize(); - (var indexBufferAuto, var indirectBufferAuto) = gd.BufferManager.GetBufferTopologyConversionIndirect( + (Auto indexBufferAuto, Auto indirectBufferAuto) = gd.BufferManager.GetBufferTopologyConversionIndirect( gd, cbs, new BufferRange(_handle, _offset, _size), diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs index ac31749cf..608b3e3df 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _blockLists.Count; i++) { - var bl = _blockLists[i]; + MemoryAllocatorBlockList bl = _blockLists[i]; if (bl.MemoryTypeIndex == memoryTypeIndex && bl.ForBuffer == isBuffer) { return bl.Allocate(size, alignment, map); @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan try { - var newBl = new MemoryAllocatorBlockList(_api, _device, memoryTypeIndex, _blockAlignment, isBuffer); + MemoryAllocatorBlockList newBl = new(_api, _device, memoryTypeIndex, _blockAlignment, isBuffer); _blockLists.Add(newBl); return newBl.Allocate(size, alignment, map); diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs index a449f841c..dd9ac723d 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Vulkan private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -101,7 +101,7 @@ namespace Ryujinx.Graphics.Vulkan private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -194,7 +194,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _blocks.Count; i++) { - var block = _blocks[i]; + Block block = _blocks[i]; if (block.Mapped == map && block.Size >= size) { @@ -213,14 +213,14 @@ namespace Ryujinx.Graphics.Vulkan ulong blockAlignedSize = BitUtils.AlignUp(size, (ulong)_blockAlignment); - var memoryAllocateInfo = new MemoryAllocateInfo + MemoryAllocateInfo memoryAllocateInfo = new() { SType = StructureType.MemoryAllocateInfo, AllocationSize = blockAlignedSize, MemoryTypeIndex = (uint)MemoryTypeIndex, }; - _api.AllocateMemory(_device, in memoryAllocateInfo, null, out var deviceMemory).ThrowOnError(); + _api.AllocateMemory(_device, in memoryAllocateInfo, null, out DeviceMemory* deviceMemory).ThrowOnError(); nint hostPointer = nint.Zero; @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Vulkan hostPointer = (nint)pointer; } - var newBlock = new Block(deviceMemory, hostPointer, blockAlignedSize); + Block newBlock = new Block(deviceMemory, hostPointer, blockAlignedSize); InsertBlock(newBlock); diff --git a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs index 51e3736aa..c3efcc8da 100644 --- a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs @@ -1,5 +1,6 @@ using Silk.NET.Core.Loader; using Silk.NET.Vulkan; +using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; @@ -18,7 +19,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK public static void Initialize() { - var configSize = (nint)Marshal.SizeOf(); + IntPtr configSize = (nint)Marshal.SizeOf(); vkGetMoltenVKConfigurationMVK(nint.Zero, out MVKConfiguration config, configSize); diff --git a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs index a6a4bdef3..b226ce1f3 100644 --- a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs @@ -232,7 +232,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Fences.Length; i++) { - var fence = Fences[i]; + FenceHolder fence = Fences[i]; if (fence != null) { @@ -256,7 +256,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Fences.Length; i++) { - var fence = Fences[i]; + FenceHolder fence = Fences[i]; if (fence != null && _bufferUsageBitmap.OverlapsWith(i, offset, size)) { diff --git a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs index 5e0ed077b..79879e04e 100644 --- a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs @@ -1,5 +1,7 @@ using Ryujinx.Graphics.GAL; +using Silk.NET.Vulkan; using System; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { @@ -16,7 +18,7 @@ namespace Ryujinx.Graphics.Vulkan private BufferHolder ResizeIfNeeded(int size) { - var flushStorage = _flushStorage; + BufferHolder flushStorage = _flushStorage; if (flushStorage == null || size > _flushStorage.Size) { @@ -31,13 +33,13 @@ namespace Ryujinx.Graphics.Vulkan public Span GetBufferData(CommandBufferPool cbp, BufferHolder buffer, int offset, int size) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); Auto srcBuffer; - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { srcBuffer = buffer.GetBuffer(cbs.CommandBuffer); - var dstBuffer = flushStorage.GetBuffer(cbs.CommandBuffer); + Auto dstBuffer = flushStorage.GetBuffer(cbs.CommandBuffer); if (srcBuffer.TryIncrementReferenceCount()) { @@ -59,12 +61,12 @@ namespace Ryujinx.Graphics.Vulkan { TextureCreateInfo info = view.Info; - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = view.GetImage().Get(cbs).Value; + Buffer buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = view.GetImage().Get(cbs).Value; view.CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, 0, 0, info.GetLayers(), info.Levels, singleSlice: false); } @@ -75,12 +77,12 @@ namespace Ryujinx.Graphics.Vulkan public Span GetTextureData(CommandBufferPool cbp, TextureView view, int size, int layer, int level) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = view.GetImage().Get(cbs).Value; + Buffer buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = view.GetImage().Get(cbs).Value; view.CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, layer, level, 1, 1, singleSlice: true); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs index cea2d9c55..da05401b6 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs @@ -1,3 +1,4 @@ +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Silk.NET.Vulkan; @@ -6,7 +7,10 @@ using System.Collections.Generic; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using BlendOp = Silk.NET.Vulkan.BlendOp; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; +using Format = Silk.NET.Vulkan.Format; using FrontFace = Ryujinx.Graphics.GAL.FrontFace; using IndexType = Ryujinx.Graphics.GAL.IndexType; using PolygonMode = Ryujinx.Graphics.GAL.PolygonMode; @@ -100,7 +104,7 @@ namespace Ryujinx.Graphics.Vulkan AutoFlush = new AutoFlushCounter(gd); EndRenderPassDelegate = EndRenderPass; - var pipelineCacheCreateInfo = new PipelineCacheCreateInfo + PipelineCacheCreateInfo pipelineCacheCreateInfo = new() { SType = StructureType.PipelineCacheCreateInfo, }; @@ -115,7 +119,7 @@ namespace Ryujinx.Graphics.Vulkan const int EmptyVbSize = 16; - using var emptyVb = gd.BufferManager.Create(gd, EmptyVbSize); + using BufferHolder emptyVb = gd.BufferManager.Create(gd, EmptyVbSize); emptyVb.SetData(0, new byte[EmptyVbSize]); _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize); _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length); @@ -172,7 +176,7 @@ namespace Ryujinx.Graphics.Vulkan { EndRenderPass(); - var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size, true).Value; + Buffer dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size, true).Value; BufferHolder.InsertBufferBarrier( Gd, @@ -215,9 +219,9 @@ namespace Ryujinx.Graphics.Vulkan BeginRenderPass(); - var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha)); - var attachment = new ClearAttachment(ImageAspectFlags.ColorBit, (uint)index, clearValue); - var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); + ClearValue clearValue = new(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha)); + ClearAttachment attachment = new(ImageAspectFlags.ColorBit, (uint)index, clearValue); + ClearRect clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect); } @@ -229,8 +233,8 @@ namespace Ryujinx.Graphics.Vulkan return; } - var clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue)); - var flags = depthMask ? ImageAspectFlags.DepthBit : 0; + ClearValue clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue)); + int flags = depthMask ? ImageAspectFlags.DepthBit : 0; if (stencilMask) { @@ -253,8 +257,8 @@ namespace Ryujinx.Graphics.Vulkan BeginRenderPass(); - var attachment = new ClearAttachment(flags, 0, clearValue); - var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); + ClearAttachment attachment = new ClearAttachment(flags, 0, clearValue); + ClearRect clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect); } @@ -268,8 +272,8 @@ namespace Ryujinx.Graphics.Vulkan { EndRenderPass(); - var src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false); - var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true); + Auto src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false); + Auto dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true); BufferHolder.Copy(Gd, Cbs, src, dst, srcOffset, dstOffset, size); } @@ -348,7 +352,7 @@ namespace Ryujinx.Graphics.Vulkan }; BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount); - var buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false); + Auto buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false); Gd.Api.CmdBindIndexBuffer(CommandBuffer, buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value, 0, Silk.NET.Vulkan.IndexType.Uint32); @@ -433,7 +437,7 @@ namespace Ryujinx.Graphics.Vulkan public void DrawIndexedIndirect(BufferRange indirectBuffer) { - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; @@ -479,11 +483,11 @@ namespace Ryujinx.Graphics.Vulkan public void DrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride) { - var countBuffer = Gd.BufferManager + Buffer countBuffer = Gd.BufferManager .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false) .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value; - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; @@ -573,7 +577,7 @@ namespace Ryujinx.Graphics.Vulkan { // TODO: Support quads and other unsupported topologies. - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size, false).Value; @@ -597,11 +601,11 @@ namespace Ryujinx.Graphics.Vulkan throw new NotSupportedException(); } - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size, false).Value; - var countBuffer = Gd.BufferManager + Buffer countBuffer = Gd.BufferManager .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false) .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size, false).Value; @@ -630,13 +634,13 @@ namespace Ryujinx.Graphics.Vulkan { if (texture is TextureView srcTexture) { - var oldCullMode = _newState.CullMode; - var oldStencilTestEnable = _newState.StencilTestEnable; - var oldDepthTestEnable = _newState.DepthTestEnable; - var oldDepthWriteEnable = _newState.DepthWriteEnable; - var oldViewports = DynamicState.Viewports; - var oldViewportsCount = _newState.ViewportsCount; - var oldTopology = _topology; + CullModeFlags oldCullMode = _newState.CullMode; + bool oldStencilTestEnable = _newState.StencilTestEnable; + bool oldDepthTestEnable = _newState.DepthTestEnable; + bool oldDepthWriteEnable = _newState.DepthWriteEnable; + Array16 oldViewports = DynamicState.Viewports; + uint oldViewportsCount = _newState.ViewportsCount; + PrimitiveTopology oldTopology = _topology; _newState.CullMode = CullModeFlags.None; _newState.StencilTestEnable = false; @@ -710,11 +714,11 @@ namespace Ryujinx.Graphics.Vulkan for (int index = 0; index < Constants.MaxRenderTargets; index++) { - ref var vkBlend = ref colorBlendAttachmentStateSpan[index]; + ref PipelineColorBlendAttachmentState vkBlend = ref colorBlendAttachmentStateSpan[index]; if (index == 0) { - var blendOp = blend.Op.Convert(); + BlendOp blendOp = blend.Op.Convert(); vkBlend = new PipelineColorBlendAttachmentState( blendEnable: true, @@ -751,7 +755,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetBlendState(int index, BlendDescriptor blend) { - ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; + ref PipelineColorBlendAttachmentState vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; if (blend.Enable) { @@ -919,7 +923,7 @@ namespace Ryujinx.Graphics.Vulkan { _topology = topology; - var vkTopology = Gd.TopologyRemap(topology).Convert(); + Silk.NET.Vulkan.PrimitiveTopology vkTopology = Gd.TopologyRemap(topology).Convert(); _newState.Topology = vkTopology; @@ -928,8 +932,8 @@ namespace Ryujinx.Graphics.Vulkan public void SetProgram(IProgram program) { - var internalProgram = (ShaderCollection)program; - var stages = internalProgram.GetInfos(); + ShaderCollection internalProgram = (ShaderCollection)program; + PipelineShaderStageCreateInfo[] stages = internalProgram.GetInfos(); _program = internalProgram; @@ -952,7 +956,7 @@ namespace Ryujinx.Graphics.Vulkan public void Specialize(in T data) where T : unmanaged { - var dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1)); + ReadOnlySpan dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1)); if (!dataSpan.SequenceEqual(_newState.SpecializationData.Span)) { @@ -988,8 +992,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var vkBlend = ref colorBlendAttachmentStateSpan[i]; - var newMask = (ColorComponentFlags)componentMask[i]; + ref PipelineColorBlendAttachmentState vkBlend = ref colorBlendAttachmentStateSpan[i]; + ColorComponentFlags newMask = (ColorComponentFlags)componentMask[i]; // When color write mask is 0, remove all blend state to help the pipeline cache. // Restore it when the mask becomes non-zero. @@ -1056,9 +1060,9 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var region = regions[i]; - var offset = new Offset2D(region.X, region.Y); - var extent = new Extent2D((uint)region.Width, (uint)region.Height); + Rectangle region = regions[i]; + Offset2D offset = new(region.X, region.Y); + Extent2D extent = new((uint)region.Width, (uint)region.Height); DynamicState.SetScissor(i, new Rect2D(offset, extent)); } @@ -1131,7 +1135,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var range = buffers[i]; + BufferRange range = buffers[i]; _transformFeedbackBuffers[i].Dispose(); @@ -1160,7 +1164,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetVertexAttribs(ReadOnlySpan vertexAttribs) { - var formatCapabilities = Gd.FormatCapabilities; + FormatCapabilities formatCapabilities = Gd.FormatCapabilities; Span newVbScalarSizes = stackalloc int[Constants.MaxVertexBuffers]; @@ -1171,9 +1175,9 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var attribute = vertexAttribs[i]; - var rawIndex = attribute.BufferIndex; - var bufferIndex = attribute.IsZero ? 0 : rawIndex + 1; + VertexAttribDescriptor attribute = vertexAttribs[i]; + int rawIndex = attribute.BufferIndex; + int bufferIndex = attribute.IsZero ? 0 : rawIndex + 1; if (!attribute.IsZero) { @@ -1192,7 +1196,7 @@ namespace Ryujinx.Graphics.Vulkan { int dirtyBit = BitOperations.TrailingZeroCount(dirtyVbSizes); - ref var buffer = ref _vertexBuffers[dirtyBit + 1]; + ref VertexBufferState buffer = ref _vertexBuffers[dirtyBit + 1]; if (buffer.AttributeScalarAlignment != newVbScalarSizes[dirtyBit]) { @@ -1220,10 +1224,10 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var vertexBuffer = vertexBuffers[i]; + VertexBufferDescriptor vertexBuffer = vertexBuffers[i]; // TODO: Support divisor > 1 - var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; + VertexInputRate inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; if (vertexBuffer.Buffer.Handle != BufferHandle.Null) { @@ -1257,7 +1261,7 @@ namespace Ryujinx.Graphics.Vulkan } } - ref var buffer = ref _vertexBuffers[binding]; + ref VertexBufferState buffer = ref _vertexBuffers[binding]; int oldScalarAlign = buffer.AttributeScalarAlignment; if (Gd.Capabilities.VertexBufferAlignment < 2 && @@ -1318,7 +1322,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var viewport = viewports[i]; + Viewport viewport = viewports[i]; DynamicState.SetViewport(i, new Silk.NET.Vulkan.Viewport( viewport.Region.X, @@ -1417,7 +1421,7 @@ namespace Ryujinx.Graphics.Vulkan continue; } - ref var vkBlend = ref colorBlendAttachmentStateSpan[i]; + ref PipelineColorBlendAttachmentState vkBlend = ref colorBlendAttachmentStateSpan[i]; for (int j = 0; j < i; j++) { @@ -1426,7 +1430,7 @@ namespace Ryujinx.Graphics.Vulkan if (colors[i] == colors[j]) { // Prefer the binding with no write mask. - ref var vkBlend2 = ref colorBlendAttachmentStateSpan[j]; + ref PipelineColorBlendAttachmentState vkBlend2 = ref colorBlendAttachmentStateSpan[j]; if (vkBlend.ColorWriteMask == 0) { colors[i] = null; @@ -1464,7 +1468,7 @@ namespace Ryujinx.Graphics.Vulkan protected void UpdatePipelineAttachmentFormats() { - var dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan(); + Span dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan(); FramebufferParams.AttachmentFormats.AsSpan(..FramebufferParams.AttachmentsCount).CopyTo(dstAttachmentFormats); _newState.Internal.AttachmentIntegerFormatMask = FramebufferParams.AttachmentIntegerFormatMask; _newState.Internal.LogicOpsAllowed = FramebufferParams.LogicOpsAllowed; @@ -1481,7 +1485,7 @@ namespace Ryujinx.Graphics.Vulkan protected unsafe void CreateRenderPass() { - var hasFramebuffer = FramebufferParams != null; + bool hasFramebuffer = FramebufferParams != null; EndRenderPass(); @@ -1686,7 +1690,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var pipeline = pbp == PipelineBindPoint.Compute + Auto pipeline = pbp == PipelineBindPoint.Compute ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache) : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass!.Get(Cbs).Value); @@ -1718,10 +1722,10 @@ namespace Ryujinx.Graphics.Vulkan { FramebufferParams.InsertLoadOpBarriers(Gd, Cbs); - var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height)); - var clearValue = new ClearValue(); + Rect2D renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height)); + ClearValue clearValue = new(); - var renderPassBeginInfo = new RenderPassBeginInfo + RenderPassBeginInfo renderPassBeginInfo = new() { SType = StructureType.RenderPassBeginInfo, RenderPass = _renderPass.Get(Cbs).Value, diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs index 9120f0b40..abc074e0c 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription + SubpassDescription subpass = new() { PipelineBindPoint = PipelineBindPoint.Graphics, }; @@ -111,11 +111,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var subpassDependency = CreateSubpassDependency(gd); + SubpassDependency subpassDependency = CreateSubpassDependency(gd); fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo + RenderPassCreateInfo renderPassCreateInfo = new() { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -126,7 +126,7 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out RenderPass* renderPass).ThrowOnError(); return new DisposableRenderPass(gd.Api, device, renderPass); } @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Vulkan public static SubpassDependency CreateSubpassDependency(VulkanRenderer gd) { - var (access, stages) = BarrierBatch.GetSubpassAccessSuperset(gd); + (AccessFlags access, PipelineStageFlags stages) = BarrierBatch.GetSubpassAccessSuperset(gd); return new SubpassDependency( 0, @@ -148,7 +148,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe static SubpassDependency2 CreateSubpassDependency2(VulkanRenderer gd) { - var (access, stages) = BarrierBatch.GetSubpassAccessSuperset(gd); + (AccessFlags access, PipelineStageFlags stages) = BarrierBatch.GetSubpassAccessSuperset(gd); return new SubpassDependency2( StructureType.SubpassDependency2, @@ -231,8 +231,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < vaCount; i++) { - var attribute = vertexAttribsSpan[i]; - var bufferIndex = attribute.IsZero ? 0 : attribute.BufferIndex + 1; + VertexAttribDescriptor attribute = vertexAttribsSpan[i]; + int bufferIndex = attribute.IsZero ? 0 : attribute.BufferIndex + 1; vertexAttributeDescriptionsSpan[i] = new VertexInputAttributeDescription( (uint)i, @@ -254,11 +254,11 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < vbCount; i++) { - var vertexBuffer = vertexBuffersSpan[i]; + BufferPipelineDescriptor vertexBuffer = vertexBuffersSpan[i]; if (vertexBuffer.Enable) { - var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; + VertexInputRate inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; int alignedStride = vertexBuffer.Stride; @@ -285,7 +285,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Constants.MaxRenderTargets; i++) { - var blend = blendDescriptorsSpan[i]; + BlendDescriptor blend = blendDescriptorsSpan[i]; if (blend.Enable && colorWriteMaskSpan[i] != 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs index c07ecf5ad..b948f8f0b 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Graphics.Vulkan private void CopyPendingQuery() { - foreach (var query in _pendingQueryCopies) + foreach (BufferedQuery query in _pendingQueryCopies) { query.PoolCopy(Cbs); } @@ -54,7 +54,7 @@ namespace Ryujinx.Graphics.Vulkan // We can't use CmdClearAttachments if not writing all components, // because on Vulkan, the pipeline state does not affect clears. // On proprietary Adreno drivers, CmdClearAttachments appears to execute out of order, so it's better to not use it at all. - var dstTexture = FramebufferParams.GetColorView(index); + TextureView dstTexture = FramebufferParams.GetColorView(index); if (dstTexture == null) { return; @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Vulkan // We can't use CmdClearAttachments if not clearing all (mask is all ones, 0xFF) or none (mask is 0) of the stencil bits, // because on Vulkan, the pipeline state does not affect clears. // On proprietary Adreno drivers, CmdClearAttachments appears to execute out of order, so it's better to not use it at all. - var dstTexture = FramebufferParams.GetDepthStencilView(); + TextureView dstTexture = FramebufferParams.GetDepthStencilView(); if (dstTexture == null) { return; @@ -246,7 +246,7 @@ namespace Ryujinx.Graphics.Vulkan AutoFlush.RegisterFlush(DrawCount); EndRenderPass(); - foreach ((var queryPool, _) in _activeQueries) + foreach ((QueryPool queryPool, _) in _activeQueries) { Gd.Api.CmdEndQuery(CommandBuffer, queryPool, 0); } @@ -271,7 +271,7 @@ namespace Ryujinx.Graphics.Vulkan _activeBufferMirrors.Clear(); - foreach ((var queryPool, var isOcclusion) in _activeQueries) + foreach ((QueryPool queryPool, bool isOcclusion) in _activeQueries) { bool isPrecise = Gd.Capabilities.SupportsPreciseOcclusionQueries && isOcclusion; diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs index 87b3342af..494447a0f 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.Vulkan if (SetDescriptors != null) { - foreach (var setDescriptor in SetDescriptors) + foreach (ResourceDescriptorCollection setDescriptor in SetDescriptors) { hasher.Add(setDescriptor); } @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan ReadOnlyCollection setDescriptors, bool usePushDescriptors) { - var key = new PlceKey(setDescriptors, usePushDescriptors); + PlceKey key = new(setDescriptors, usePushDescriptors); return _plces.GetOrAdd(key, _ => new PipelineLayoutCacheEntry(gd, device, setDescriptors, usePushDescriptors)); } @@ -90,7 +90,7 @@ namespace Ryujinx.Graphics.Vulkan { if (disposing) { - foreach (var plce in _plces.Values) + foreach (PipelineLayoutCacheEntry plce in _plces.Values) { plce.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs index 83443f691..c943d1e45 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan { int count = 0; - foreach (var descriptor in setDescriptors[setIndex].Descriptors) + foreach (ResourceDescriptor descriptor in setDescriptors[setIndex].Descriptors) { count += descriptor.Count; } @@ -148,11 +148,11 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetNewDescriptorSetCollection(int setIndex, out bool isNew) { - var list = _currentDsCache[setIndex]; + List> list = _currentDsCache[setIndex]; int index = _dsCacheCursor[setIndex]++; if (index == list.Count) { - var dsc = _descriptorSetManager.AllocateDescriptorSet( + Auto dsc = _descriptorSetManager.AllocateDescriptorSet( _gd.Api, DescriptorSetLayouts[setIndex], _poolSizes[setIndex], @@ -173,8 +173,8 @@ namespace Ryujinx.Graphics.Vulkan { FreeCompletedManualDescriptorSets(); - var list = _manualDsCache[setIndex] ??= []; - var span = CollectionsMarshal.AsSpan(list); + List list = _manualDsCache[setIndex] ??= []; + Span span = CollectionsMarshal.AsSpan(list); Queue freeQueue = _freeManualDsCacheEntries[setIndex]; @@ -195,7 +195,7 @@ namespace Ryujinx.Graphics.Vulkan } // Otherwise create a new descriptor set, and add to our pending queue for command buffer consumption tracking. - var dsc = _descriptorSetManager.AllocateDescriptorSet( + Auto dsc = _descriptorSetManager.AllocateDescriptorSet( _gd.Api, DescriptorSetLayouts[setIndex], _poolSizes[setIndex], @@ -214,9 +214,9 @@ namespace Ryujinx.Graphics.Vulkan { FreeCompletedManualDescriptorSets(); - var list = _manualDsCache[setIndex]; - var span = CollectionsMarshal.AsSpan(list); - ref var entry = ref span[cacheIndex]; + List list = _manualDsCache[setIndex]; + Span span = CollectionsMarshal.AsSpan(list); + ref ManualDescriptorSetEntry entry = ref span[cacheIndex]; uint cbMask = 1u << cbs.CommandBufferIndex; @@ -231,15 +231,15 @@ namespace Ryujinx.Graphics.Vulkan private void FreeCompletedManualDescriptorSets() { FenceHolder signalledFence = null; - while (_pendingManualDsConsumptions.TryPeek(out var pds) && pds.Fence != null && (pds.Fence == signalledFence || pds.Fence.IsSignaled())) + while (_pendingManualDsConsumptions.TryPeek(out PendingManualDsConsumption pds) && pds.Fence != null && (pds.Fence == signalledFence || pds.Fence.IsSignaled())) { signalledFence = pds.Fence; // Already checked - don't need to do it again. - var dequeued = _pendingManualDsConsumptions.Dequeue(); + PendingManualDsConsumption dequeued = _pendingManualDsConsumptions.Dequeue(); Debug.Assert(dequeued.Fence == pds.Fence); pds.Fence.Put(); - var span = CollectionsMarshal.AsSpan(_manualDsCache[dequeued.SetIndex]); - ref var entry = ref span[dequeued.CacheIndex]; + Span span = CollectionsMarshal.AsSpan(_manualDsCache[dequeued.SetIndex]); + ref ManualDescriptorSetEntry entry = ref span[dequeued.CacheIndex]; entry.CbRefMask &= ~(1u << dequeued.CommandBufferIndex); if (!entry.InUse && entry.CbRefMask == 0) @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Vulkan public void ReleaseManualDescriptorSetCollection(int setIndex, int cacheIndex) { - var list = _manualDsCache[setIndex]; - var span = CollectionsMarshal.AsSpan(list); + List list = _manualDsCache[setIndex]; + Span span = CollectionsMarshal.AsSpan(list); span[cacheIndex].InUse = false; @@ -366,7 +366,7 @@ namespace Ryujinx.Graphics.Vulkan _gd.Api.DestroyDescriptorSetLayout(_device, DescriptorSetLayouts[i], null); } - while (_pendingManualDsConsumptions.TryDequeue(out var pds)) + while (_pendingManualDsConsumptions.TryDequeue(out PendingManualDsConsumption pds)) { pds.Fence.Put(); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs index 666a57ab1..612a8b25d 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan updateAfterBindFlags[setIndex] = true; } - var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo + DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = new() { SType = StructureType.DescriptorSetLayoutCreateInfo, PBindings = pLayoutBindings, @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorSetLayout* pLayouts = layouts) { - var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo + PipelineLayoutCreateInfo pipelineLayoutCreateInfo = new() { SType = StructureType.PipelineLayoutCreateInfo, PSetLayouts = pLayouts, diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs index a4e571b4f..9adb651b4 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs @@ -335,12 +335,12 @@ namespace Ryujinx.Graphics.Vulkan ShaderCollection program, PipelineCache cache) { - if (program.TryGetComputePipeline(ref SpecializationData, out var pipeline)) + if (program.TryGetComputePipeline(ref SpecializationData, out Auto pipeline)) { return pipeline; } - var pipelineCreateInfo = new ComputePipelineCreateInfo + ComputePipelineCreateInfo pipelineCreateInfo = new() { SType = StructureType.ComputePipelineCreateInfo, Stage = Stages[0], @@ -352,7 +352,7 @@ namespace Ryujinx.Graphics.Vulkan bool hasSpec = program.SpecDescriptions != null; - var desc = hasSpec ? program.SpecDescriptions[0] : SpecDescription.Empty; + SpecDescription desc = hasSpec ? program.SpecDescriptions[0] : SpecDescription.Empty; if (hasSpec && SpecializationData.Length < (int)desc.Info.DataSize) { @@ -391,7 +391,7 @@ namespace Ryujinx.Graphics.Vulkan RenderPass renderPass, bool throwOnError = false) { - if (program.TryGetGraphicsPipeline(ref Internal, out var pipeline)) + if (program.TryGetGraphicsPipeline(ref Internal, out Auto pipeline)) { return pipeline; } @@ -410,7 +410,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (VertexInputBindingDescription* pVertexBindingDescriptions = &Internal.VertexBindingDescriptions[0]) fixed (PipelineColorBlendAttachmentState* pColorBlendAttachmentState = &Internal.ColorBlendAttachmentState[0]) { - var vertexInputState = new PipelineVertexInputStateCreateInfo + PipelineVertexInputStateCreateInfo vertexInputState = new() { SType = StructureType.PipelineVertexInputStateCreateInfo, VertexAttributeDescriptionCount = VertexAttributeDescriptionsCount, @@ -447,20 +447,20 @@ namespace Ryujinx.Graphics.Vulkan primitiveRestartEnable &= topologySupportsRestart; - var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo + PipelineInputAssemblyStateCreateInfo inputAssemblyState = new() { SType = StructureType.PipelineInputAssemblyStateCreateInfo, PrimitiveRestartEnable = primitiveRestartEnable, Topology = HasTessellationControlShader ? PrimitiveTopology.PatchList : Topology, }; - var tessellationState = new PipelineTessellationStateCreateInfo + PipelineTessellationStateCreateInfo tessellationState = new() { SType = StructureType.PipelineTessellationStateCreateInfo, PatchControlPoints = PatchControlPoints, }; - var rasterizationState = new PipelineRasterizationStateCreateInfo + PipelineRasterizationStateCreateInfo rasterizationState = new() { SType = StructureType.PipelineRasterizationStateCreateInfo, DepthClampEnable = DepthClampEnable, @@ -472,7 +472,7 @@ namespace Ryujinx.Graphics.Vulkan DepthBiasEnable = DepthBiasEnable, }; - var viewportState = new PipelineViewportStateCreateInfo + PipelineViewportStateCreateInfo viewportState = new() { SType = StructureType.PipelineViewportStateCreateInfo, ViewportCount = ViewportsCount, @@ -490,7 +490,7 @@ namespace Ryujinx.Graphics.Vulkan viewportState.PNext = &viewportDepthClipControlState; } - var multisampleState = new PipelineMultisampleStateCreateInfo + PipelineMultisampleStateCreateInfo multisampleState = new() { SType = StructureType.PipelineMultisampleStateCreateInfo, SampleShadingEnable = false, @@ -500,19 +500,19 @@ namespace Ryujinx.Graphics.Vulkan AlphaToOneEnable = AlphaToOneEnable, }; - var stencilFront = new StencilOpState( + StencilOpState stencilFront = new( StencilFrontFailOp, StencilFrontPassOp, StencilFrontDepthFailOp, StencilFrontCompareOp); - var stencilBack = new StencilOpState( + StencilOpState stencilBack = new( StencilBackFailOp, StencilBackPassOp, StencilBackDepthFailOp, StencilBackCompareOp); - var depthStencilState = new PipelineDepthStencilStateCreateInfo + PipelineDepthStencilStateCreateInfo depthStencilState = new() { SType = StructureType.PipelineDepthStencilStateCreateInfo, DepthTestEnable = DepthTestEnable, @@ -549,7 +549,7 @@ namespace Ryujinx.Graphics.Vulkan // so we need to force disable them here. bool logicOpEnable = LogicOpEnable && (gd.Vendor == Vendor.Nvidia || Internal.LogicOpsAllowed); - var colorBlendState = new PipelineColorBlendStateCreateInfo + PipelineColorBlendStateCreateInfo colorBlendState = new() { SType = StructureType.PipelineColorBlendStateCreateInfo, LogicOpEnable = logicOpEnable, @@ -598,7 +598,7 @@ namespace Ryujinx.Graphics.Vulkan dynamicStates[dynamicStatesCount++] = DynamicState.AttachmentFeedbackLoopEnableExt; } - var pipelineDynamicStateCreateInfo = new PipelineDynamicStateCreateInfo + PipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo = new() { SType = StructureType.PipelineDynamicStateCreateInfo, DynamicStateCount = (uint)dynamicStatesCount, @@ -622,7 +622,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var pipelineCreateInfo = new GraphicsPipelineCreateInfo + GraphicsPipelineCreateInfo pipelineCreateInfo = new() { SType = StructureType.GraphicsPipelineCreateInfo, Flags = flags, @@ -692,12 +692,12 @@ namespace Ryujinx.Graphics.Vulkan for (int index = 0; index < VertexAttributeDescriptionsCount; index++) { - var attribute = vertexAttributeDescriptionsSpan[index]; + VertexInputAttributeDescription attribute = vertexAttributeDescriptionsSpan[index]; int vbIndex = GetVertexBufferIndex(attribute.Binding); if (vbIndex >= 0) { - ref var vb = ref vertexBindingDescriptionsSpan[vbIndex]; + ref VertexInputBindingDescription vb = ref vertexBindingDescriptionsSpan[vbIndex]; Format format = attribute.Format; diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs index 5d48a6622..5377c8a1e 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs @@ -4,6 +4,7 @@ using Silk.NET.Vulkan; using System; using System.Runtime.InteropServices; using System.Threading; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan.Queries { @@ -44,7 +45,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries QueryPipelineStatisticFlags flags = type == CounterType.PrimitivesGenerated ? QueryPipelineStatisticFlags.GeometryShaderPrimitivesBit : 0; - var queryPoolCreateInfo = new QueryPoolCreateInfo + QueryPoolCreateInfo queryPoolCreateInfo = new() { SType = StructureType.QueryPoolCreateInfo, QueryCount = 1, @@ -55,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries gd.Api.CreateQueryPool(device, in queryPoolCreateInfo, null, out _queryPool).ThrowOnError(); } - var buffer = gd.BufferManager.Create(gd, sizeof(long), forConditionalRendering: true); + BufferHolder buffer = gd.BufferManager.Create(gd, sizeof(long), forConditionalRendering: true); _bufferMap = buffer.Map(0, sizeof(long)); _defaultValue = result32Bit ? DefaultValueInt : DefaultValue; @@ -183,7 +184,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void PoolCopy(CommandBufferScoped cbs) { - var buffer = _buffer.GetBuffer(cbs.CommandBuffer, true).Get(cbs, 0, sizeof(long), true).Value; + Buffer buffer = _buffer.GetBuffer(cbs.CommandBuffer, true).Get(cbs, 0, sizeof(long), true).Value; QueryResultFlags flags = QueryResultFlags.ResultWaitBit; diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs b/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs index 518ede5f3..2a87be3af 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void ResetCounterPool() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.ResetCounterPool(); } @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void Update() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Flush(false); } @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void Dispose() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs b/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs index 7c57b8feb..c3c3c2c61 100644 --- a/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs +++ b/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs @@ -22,7 +22,7 @@ namespace Ryujinx.Graphics.Vulkan if (_colors != null) { - foreach (var color in _colors) + foreach (TextureView color in _colors) { hc.Add(color); } diff --git a/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs b/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs index 6cf413de7..b608e8d37 100644 --- a/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs @@ -47,14 +47,14 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription + SubpassDescription subpass = new() { PipelineBindPoint = PipelineBindPoint.Graphics, }; AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments]; - var hasFramebuffer = fb != null; + bool hasFramebuffer = fb != null; if (hasFramebuffer && fb.AttachmentsCount != 0) { @@ -110,11 +110,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var subpassDependency = PipelineConverter.CreateSubpassDependency(gd); + SubpassDependency subpassDependency = PipelineConverter.CreateSubpassDependency(gd); fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo + RenderPassCreateInfo renderPassCreateInfo = new() { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -125,7 +125,7 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out RenderPass* renderPass).ThrowOnError(); _renderPass = new Auto(new DisposableRenderPass(gd.Api, device, renderPass)); } @@ -136,9 +136,9 @@ namespace Ryujinx.Graphics.Vulkan if (hasFramebuffer) { - var textures = fb.GetAttachmentViews(); + TextureView[] textures = fb.GetAttachmentViews(); - foreach (var texture in textures) + foreach (TextureView texture in textures) { texture.AddRenderPass(key, this); } @@ -153,7 +153,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetFramebuffer(VulkanRenderer gd, CommandBufferScoped cbs, FramebufferParams fb) { - var key = new FramebufferCacheKey(fb.Width, fb.Height, fb.Layers); + FramebufferCacheKey key = new(fb.Width, fb.Height, fb.Layers); if (!_framebuffers.TryGetValue(ref key, out Auto result)) { @@ -204,14 +204,14 @@ namespace Ryujinx.Graphics.Vulkan { // Dispose all framebuffers. - foreach (var fb in _framebuffers.Values) + foreach (Auto fb in _framebuffers.Values) { fb.Dispose(); } // Notify all texture views that this render pass has been disposed. - foreach (var texture in _textures) + foreach (TextureView texture in _textures) { texture.RemoveRenderPass(_key); } diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs b/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs index f96b4a845..c97676858 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs @@ -42,7 +42,7 @@ namespace Ryujinx.Graphics.Vulkan return true; } - var dsc = program.GetNewManualDescriptorSetCollection(cbs, setIndex, out _cachedDscIndex).Get(cbs); + DescriptorSetCollection dsc = program.GetNewManualDescriptorSetCollection(cbs, setIndex, out _cachedDscIndex).Get(cbs); sets = dsc.GetSets(); diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs index 89b788dd2..57de355e9 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs @@ -42,8 +42,8 @@ namespace Ryujinx.Graphics.Vulkan public ResourceLayout Build() { - var descriptors = new ResourceDescriptorCollection[TotalSets]; - var usages = new ResourceUsageCollection[TotalSets]; + ResourceDescriptorCollection[] descriptors = new ResourceDescriptorCollection[TotalSets]; + ResourceUsageCollection[] usages = new ResourceUsageCollection[TotalSets]; for (int index = 0; index < TotalSets; index++) { diff --git a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs index 97fe17c4a..70c207f69 100644 --- a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs @@ -26,9 +26,9 @@ namespace Ryujinx.Graphics.Vulkan maxLod = 0.25f; } - var borderColor = GetConstrainedBorderColor(info.BorderColor, out var cantConstrain); + BorderColor borderColor = GetConstrainedBorderColor(info.BorderColor, out bool cantConstrain); - var samplerCreateInfo = new Silk.NET.Vulkan.SamplerCreateInfo + Silk.NET.Vulkan.SamplerCreateInfo samplerCreateInfo = new() { SType = StructureType.SamplerCreateInfo, MagFilter = info.MagFilter.Convert(), @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Vulkan if (cantConstrain && gd.Capabilities.SupportsCustomBorderColor) { - var color = new ClearColorValue( + ClearColorValue color = new( info.BorderColor.Red, info.BorderColor.Green, info.BorderColor.Blue, @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Vulkan samplerCreateInfo.BorderColor = BorderColor.FloatCustomExt; } - gd.Api.CreateSampler(device, in samplerCreateInfo, null, out var sampler).ThrowOnError(); + gd.Api.CreateSampler(device, in samplerCreateInfo, null, out Sampler* sampler).ThrowOnError(); _sampler = new Auto(new DisposableSampler(gd.Api, device, sampler)); } diff --git a/src/Ryujinx.Graphics.Vulkan/Shader.cs b/src/Ryujinx.Graphics.Vulkan/Shader.cs index 8aaca03b7..811b80d72 100644 --- a/src/Ryujinx.Graphics.Vulkan/Shader.cs +++ b/src/Ryujinx.Graphics.Vulkan/Shader.cs @@ -54,7 +54,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (byte* pCode = spirv) { - var shaderModuleCreateInfo = new ShaderModuleCreateInfo + ShaderModuleCreateInfo shaderModuleCreateInfo = new() { SType = StructureType.ShaderModuleCreateInfo, CodeSize = (uint)spirv.Length, @@ -89,7 +89,7 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var spirvBytes = new Span(api.ResultGetBytes(scr), (int)api.ResultGetLength(scr)); + Span spirvBytes = new(api.ResultGetBytes(scr), (int)api.ResultGetLength(scr)); byte[] code = new byte[(spirvBytes.Length + 3) & ~3]; diff --git a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs index 0ed1b2774..50a1b52f4 100644 --- a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan gd.Shaders.Add(this); - var internalShaders = new Shader[shaders.Length]; + Shader[] internalShaders = new Shader[shaders.Length]; _infos = new PipelineShaderStageCreateInfo[shaders.Length]; @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < shaders.Length; i++) { - var shader = new Shader(gd.Api, device, shaders[i]); + Shader shader = new(gd.Api, device, shaders[i]); stages |= 1u << shader.StageFlags switch { @@ -174,7 +174,7 @@ namespace Ryujinx.Graphics.Vulkan // Can't use any of the reserved usages. for (int i = 0; i < uniformUsage.Count; i++) { - var binding = uniformUsage[i].Binding; + int binding = uniformUsage[i].Binding; if (reserved.Contains(binding) || binding >= Constants.MaxPushDescriptorBinding || @@ -194,7 +194,7 @@ namespace Ryujinx.Graphics.Vulkan // The reserved bindings were selected when determining if push descriptors could be used. int[] reserved = gd.GetPushDescriptorReservedBindings(false); - var result = new ResourceDescriptorCollection[sets.Count]; + ResourceDescriptorCollection[] result = new ResourceDescriptorCollection[sets.Count]; for (int i = 0; i < sets.Count; i++) { @@ -203,7 +203,7 @@ namespace Ryujinx.Graphics.Vulkan // Push descriptors apply here. Remove reserved bindings. ResourceDescriptorCollection original = sets[i]; - var pdUniforms = new ResourceDescriptor[original.Descriptors.Count]; + ResourceDescriptor[] pdUniforms = new ResourceDescriptor[original.Descriptors.Count]; int j = 0; foreach (ResourceDescriptor descriptor in original.Descriptors) @@ -356,7 +356,7 @@ namespace Ryujinx.Graphics.Vulkan private DescriptorSetTemplate[] BuildTemplates(bool usePushDescriptors) { - var templates = new DescriptorSetTemplate[BindingSegments.Length]; + DescriptorSetTemplate[] templates = new DescriptorSetTemplate[BindingSegments.Length]; for (int setIndex = 0; setIndex < BindingSegments.Length; setIndex++) { @@ -425,9 +425,9 @@ namespace Ryujinx.Graphics.Vulkan PipelineStageFlags buffer = PipelineStageFlags.None; PipelineStageFlags texture = PipelineStageFlags.None; - foreach (var set in setUsages) + foreach (ResourceUsageCollection set in setUsages) { - foreach (var range in set.Usages) + foreach (ResourceUsage range in set.Usages) { if (range.Write) { @@ -496,7 +496,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _shaders.Length; i++) { - var shader = _shaders[i]; + Shader shader = _shaders[i]; if (shader.CompileStatus != ProgramLinkStatus.Success) { @@ -555,12 +555,12 @@ namespace Ryujinx.Graphics.Vulkan // First, we need to create a render pass object compatible with the one that will be used at runtime. // The active attachment formats have been provided by the abstraction layer. - var renderPass = CreateDummyRenderPass(); + DisposableRenderPass renderPass = CreateDummyRenderPass(); PipelineState pipeline = _state.ToVulkanPipelineState(_gd); // Copy the shader stage info to the pipeline. - var stages = pipeline.Stages.AsSpan(); + Span stages = pipeline.Stages.AsSpan(); for (int i = 0; i < _shaders.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs index ecb2abfc6..73303685b 100644 --- a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs +++ b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Map.Length; ++i) { - var typeSize = SizeOf(description[i].Type); + uint typeSize = SizeOf(description[i].Type); Map[i] = new SpecializationMapEntry(description[i].Id, structSize, typeSize); structSize += typeSize; } @@ -89,7 +89,7 @@ namespace Ryujinx.Graphics.Vulkan _data = new byte[data.Length]; data.CopyTo(_data); - var hc = new HashCode(); + HashCode hc = new(); hc.AddBytes(data); _hash = hc.ToHashCode(); } diff --git a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs index 75fb38580..7a8801def 100644 --- a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs @@ -107,8 +107,8 @@ namespace Ryujinx.Graphics.Vulkan private void PushDataImpl(CommandBufferScoped cbs, BufferHolder dst, int dstOffset, ReadOnlySpan data) { - var srcBuffer = _buffer.GetBuffer(); - var dstBuffer = dst.GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true); + Auto srcBuffer = _buffer.GetBuffer(); + Auto dstBuffer = dst.GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true); int offset = _freeOffset; int capacity = BufferSize - offset; @@ -242,7 +242,7 @@ namespace Ryujinx.Graphics.Vulkan private bool WaitFreeCompleted(CommandBufferPool cbp) { - if (_pendingCopies.TryPeek(out var pc)) + if (_pendingCopies.TryPeek(out PendingCopy pc)) { if (!pc.Fence.IsSignaled()) { @@ -254,7 +254,7 @@ namespace Ryujinx.Graphics.Vulkan pc.Fence.Wait(); } - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -266,10 +266,10 @@ namespace Ryujinx.Graphics.Vulkan public void FreeCompleted() { FenceHolder signalledFence = null; - while (_pendingCopies.TryPeek(out var pc) && pc.Fence != null && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) + while (_pendingCopies.TryPeek(out PendingCopy pc) && pc.Fence != null && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) { signalledFence = pc.Fence; // Already checked - don't need to do it again. - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -282,7 +282,7 @@ namespace Ryujinx.Graphics.Vulkan { _gd.BufferManager.Delete(Handle); - while (_pendingCopies.TryDequeue(out var pc)) + while (_pendingCopies.TryDequeue(out PendingCopy pc)) { pc.Fence.Put(); } diff --git a/src/Ryujinx.Graphics.Vulkan/TextureArray.cs b/src/Ryujinx.Graphics.Vulkan/TextureArray.cs index ca8cf7911..2511f5711 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureArray.cs @@ -148,8 +148,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < textures.Length; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[i]; if (i > 0 && _textureRefs[i - 1].View == refs.View && _textureRefs[i - 1].Sampler == refs.Sampler) { diff --git a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs index fce3726a8..0fe5b539f 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs @@ -36,8 +36,8 @@ namespace Ryujinx.Graphics.Vulkan return Math.Clamp(value, 0, max); } - var xy1 = new Offset3D(Clamp(extents.X1, width) >> level, Clamp(extents.Y1, height) >> level, 0); - var xy2 = new Offset3D(Clamp(extents.X2, width) >> level, Clamp(extents.Y2, height) >> level, 1); + Offset3D xy1 = new(Clamp(extents.X1, width) >> level, Clamp(extents.Y1, height) >> level, 0); + Offset3D xy2 = new(Clamp(extents.X2, width) >> level, Clamp(extents.Y2, height) >> level, 1); return (xy1, xy2); } @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Vulkan var srcOffsets = new ImageBlit.SrcOffsetsBuffer(); var dstOffsets = new ImageBlit.DstOffsetsBuffer(); - var filter = linearFilter && !dstInfo.Format.IsDepthOrStencil() ? Filter.Linear : Filter.Nearest; + Filter filter = linearFilter && !dstInfo.Format.IsDepthOrStencil() ? Filter.Linear : Filter.Nearest; TextureView.InsertImageBarrier( api, @@ -83,8 +83,8 @@ namespace Ryujinx.Graphics.Vulkan for (int level = 0; level < levels; level++) { - var srcSl = new ImageSubresourceLayers(srcAspectFlags, copySrcLevel, (uint)srcLayer, (uint)layers); - var dstSl = new ImageSubresourceLayers(dstAspectFlags, copyDstLevel, (uint)dstLayer, (uint)layers); + ImageSubresourceLayers srcSl = new(srcAspectFlags, copySrcLevel, (uint)srcLayer, (uint)layers); + ImageSubresourceLayers dstSl = new(dstAspectFlags, copyDstLevel, (uint)dstLayer, (uint)layers); (srcOffsets.Element0, srcOffsets.Element1) = ExtentsToOffset3D(srcRegion, srcInfo.Width, srcInfo.Height, level); (dstOffsets.Element0, dstOffsets.Element1) = ExtentsToOffset3D(dstRegion, dstInfo.Width, dstInfo.Height, level); @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Vulkan (srcOffsets.Element0, srcOffsets.Element1) = ClampOffsetsToMip(srcOffsets.Element0, srcOffsets.Element1, srcMipW, srcMipH); (dstOffsets.Element0, dstOffsets.Element1) = ClampOffsetsToMip(dstOffsets.Element0, dstOffsets.Element1, dstMipW, dstMipH); - var region = new ImageBlit + ImageBlit region = new() { SrcSubresource = srcSl, SrcOffsets = srcOffsets, @@ -322,13 +322,13 @@ namespace Ryujinx.Graphics.Vulkan break; } - var srcSl = new ImageSubresourceLayers( + ImageSubresourceLayers srcSl = new( srcAspect, (uint)(srcViewLevel + srcLevel + level), (uint)(srcViewLayer + srcLayer), (uint)srcLayers); - var dstSl = new ImageSubresourceLayers( + ImageSubresourceLayers dstSl = new( dstAspect, (uint)(dstViewLevel + dstLevel + level), (uint)(dstViewLayer + dstLayer), @@ -345,17 +345,17 @@ namespace Ryujinx.Graphics.Vulkan copyWidth = Math.Min(copyWidth, Math.Min(srcMipW, dstMipW)); copyHeight = Math.Min(copyHeight, Math.Min(srcMipH, dstMipH)); - var extent = new Extent3D((uint)copyWidth, (uint)copyHeight, (uint)srcDepth); + Extent3D extent = new((uint)copyWidth, (uint)copyHeight, (uint)srcDepth); if (srcInfo.Samples > 1 && srcInfo.Samples != dstInfo.Samples) { - var region = new ImageResolve(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); + ImageResolve region = new(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); api.CmdResolveImage(commandBuffer, srcImage, ImageLayout.General, dstImage, ImageLayout.General, 1, in region); } else { - var region = new ImageCopy(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); + ImageCopy region = new(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); api.CmdCopyImage(commandBuffer, srcImage, ImageLayout.General, dstImage, ImageLayout.General, 1, in region); } @@ -391,10 +391,10 @@ namespace Ryujinx.Graphics.Vulkan TextureView src, TextureView dst) { - var dsAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 0, ImageLayout.General); - var dsResolveAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 1, ImageLayout.General); + AttachmentReference2 dsAttachmentReference = new(StructureType.AttachmentReference2, null, 0, ImageLayout.General); + AttachmentReference2 dsResolveAttachmentReference = new(StructureType.AttachmentReference2, null, 1, ImageLayout.General); - var subpassDsResolve = new SubpassDescriptionDepthStencilResolve + SubpassDescriptionDepthStencilResolve subpassDsResolve = new() { SType = StructureType.SubpassDescriptionDepthStencilResolve, PDepthStencilResolveAttachment = &dsResolveAttachmentReference, @@ -402,7 +402,7 @@ namespace Ryujinx.Graphics.Vulkan StencilResolveMode = ResolveModeFlags.SampleZeroBit, }; - var subpass = new SubpassDescription2 + SubpassDescription2 subpass = new() { SType = StructureType.SubpassDescription2, PipelineBindPoint = PipelineBindPoint.Graphics, @@ -438,11 +438,11 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout.General, ImageLayout.General); - var subpassDependency = PipelineConverter.CreateSubpassDependency2(gd); + SubpassDependency2 subpassDependency = PipelineConverter.CreateSubpassDependency2(gd); fixed (AttachmentDescription2* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo2 + RenderPassCreateInfo2 renderPassCreateInfo = new() { SType = StructureType.RenderPassCreateInfo2, PAttachments = pAttachmentDescs, @@ -453,19 +453,19 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass2(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass2(device, in renderPassCreateInfo, null, out RenderPass* renderPass).ThrowOnError(); - using var rp = new Auto(new DisposableRenderPass(gd.Api, device, renderPass)); + using Auto rp = new(new DisposableRenderPass(gd.Api, device, renderPass)); ImageView* attachments = stackalloc ImageView[2]; - var srcView = src.GetImageViewForAttachment(); - var dstView = dst.GetImageViewForAttachment(); + Auto srcView = src.GetImageViewForAttachment(); + Auto dstView = dst.GetImageViewForAttachment(); attachments[0] = srcView.Get(cbs).Value; attachments[1] = dstView.Get(cbs).Value; - var framebufferCreateInfo = new FramebufferCreateInfo + FramebufferCreateInfo framebufferCreateInfo = new() { SType = StructureType.FramebufferCreateInfo, RenderPass = rp.Get(cbs).Value, @@ -476,13 +476,13 @@ namespace Ryujinx.Graphics.Vulkan Layers = (uint)src.Layers, }; - gd.Api.CreateFramebuffer(device, in framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); - using var fb = new Auto(new DisposableFramebuffer(gd.Api, device, framebuffer), null, srcView, dstView); + gd.Api.CreateFramebuffer(device, in framebufferCreateInfo, null, out Framebuffer* framebuffer).ThrowOnError(); + using Auto fb = new(new DisposableFramebuffer(gd.Api, device, framebuffer), null, srcView, dstView); - var renderArea = new Rect2D(null, new Extent2D((uint)src.Info.Width, (uint)src.Info.Height)); - var clearValue = new ClearValue(); + Rect2D renderArea = new Rect2D(null, new Extent2D((uint)src.Info.Width, (uint)src.Info.Height)); + ClearValue clearValue = new(); - var renderPassBeginInfo = new RenderPassBeginInfo + RenderPassBeginInfo renderPassBeginInfo = new() { SType = StructureType.RenderPassBeginInfo, RenderPass = rp.Get(cbs).Value, diff --git a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs index 7c04336d3..754be9de0 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs @@ -81,19 +81,19 @@ namespace Ryujinx.Graphics.Vulkan bool isMsImageStorageSupported = gd.Capabilities.SupportsShaderStorageImageMultisample || !info.Target.IsMultisample(); - var format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); - var levels = (uint)info.Levels; - var layers = (uint)info.GetLayers(); - var depth = (uint)(info.Target == Target.Texture3D ? info.Depth : 1); + VkFormat format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); + uint levels = (uint)info.Levels; + uint layers = (uint)info.GetLayers(); + uint depth = (uint)(info.Target == Target.Texture3D ? info.Depth : 1); VkFormat = format; _depthOrLayers = info.GetDepthOrLayers(); - var type = info.Target.Convert(); + ImageType type = info.Target.Convert(); - var extent = new Extent3D((uint)info.Width, (uint)info.Height, depth); + Extent3D extent = new((uint)info.Width, (uint)info.Height, depth); - var sampleCountFlags = ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)info.Samples); + SampleCountFlags sampleCountFlags = ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)info.Samples); ImageUsageFlags usage = GetImageUsage(info.Format, info.Target, gd.Capabilities, isMsImageStorageSupported); UsageFlags = usage; @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan flags |= ImageCreateFlags.Create2DArrayCompatibleBit; } - var imageCreateInfo = new ImageCreateInfo + ImageCreateInfo imageCreateInfo = new() { SType = StructureType.ImageCreateInfo, ImageType = type, @@ -134,8 +134,8 @@ namespace Ryujinx.Graphics.Vulkan if (foreignAllocation == null) { - gd.Api.GetImageMemoryRequirements(device, _image, out var requirements); - var allocation = gd.MemoryAllocator.AllocateDeviceMemory(requirements, DefaultImageMemoryFlags); + gd.Api.GetImageMemoryRequirements(device, _image, out MemoryRequirements requirements); + MemoryAllocation allocation = gd.MemoryAllocator.AllocateDeviceMemory(requirements, DefaultImageMemoryFlags); if (allocation.Memory.Handle == 0UL) { @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan { _foreignAllocationAuto = foreignAllocation; foreignAllocation.IncrementReferenceCount(); - var allocation = foreignAllocation.GetUnsafe(); + MemoryAllocation allocation = foreignAllocation.GetUnsafe(); gd.Api.BindImageMemory(device, _image, allocation.Memory, allocation.Offset).ThrowOnError(); @@ -170,7 +170,7 @@ namespace Ryujinx.Graphics.Vulkan public TextureStorage CreateAliasedColorForDepthStorageUnsafe(Format format) { - var colorFormat = format switch + Format colorFormat = format switch { Format.S8Uint => Format.R8Unorm, Format.D16Unorm => Format.R16Unorm, @@ -185,11 +185,11 @@ namespace Ryujinx.Graphics.Vulkan public TextureStorage CreateAliasedStorageUnsafe(Format format) { - if (_aliasedStorages == null || !_aliasedStorages.TryGetValue(format, out var storage)) + if (_aliasedStorages == null || !_aliasedStorages.TryGetValue(format, out TextureStorage storage)) { _aliasedStorages ??= new Dictionary(); - var info = NewCreateInfoWith(ref _info, format, _info.BytesPerPixel); + TextureCreateInfo info = NewCreateInfoWith(ref _info, format, _info.BytesPerPixel); storage = new TextureStorage(_gd, _device, info, _allocationAuto); @@ -275,11 +275,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var aspectFlags = _info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = _info.Format.ConvertAspectFlags(); - var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, (uint)_info.Levels, 0, (uint)_info.GetLayers()); + ImageSubresourceRange subresourceRange = new(aspectFlags, 0, (uint)_info.Levels, 0, (uint)_info.GetLayers()); - var barrier = new ImageMemoryBarrier + ImageMemoryBarrier barrier = new() { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = 0, @@ -312,7 +312,7 @@ namespace Ryujinx.Graphics.Vulkan public static ImageUsageFlags GetImageUsage(Format format, Target target, in HardwareCapabilities capabilities, bool isMsImageStorageSupported) { - var usage = DefaultUsageFlags; + ImageUsageFlags usage = DefaultUsageFlags; if (format.IsDepthOrStencil()) { @@ -405,17 +405,17 @@ namespace Ryujinx.Graphics.Vulkan int rowLength = (Info.GetMipStride(level) / Info.BytesPerPixel) * Info.BlockWidth; - var sl = new ImageSubresourceLayers( + ImageSubresourceLayers sl = new( aspectFlags, (uint)(dstLevel + level), (uint)layer, (uint)layers); - var extent = new Extent3D((uint)width, (uint)height, (uint)depth); + Extent3D extent = new((uint)width, (uint)height, (uint)depth); int z = is3D ? dstLayer : 0; - var region = new BufferImageCopy( + BufferImageCopy region = new( (ulong)offset, (uint)BitUtils.AlignUp(rowLength, Info.BlockWidth), (uint)BitUtils.AlignUp(height, Info.BlockHeight), @@ -604,7 +604,7 @@ namespace Ryujinx.Graphics.Vulkan if (_aliasedStorages != null) { - foreach (var storage in _aliasedStorages.Values) + foreach (TextureStorage storage in _aliasedStorages.Values) { storage.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/TextureView.cs b/src/Ryujinx.Graphics.Vulkan/TextureView.cs index d210fc3d0..9af4392cb 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureView.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureView.cs @@ -63,20 +63,20 @@ namespace Ryujinx.Graphics.Vulkan bool isMsImageStorageSupported = gd.Capabilities.SupportsShaderStorageImageMultisample || !info.Target.IsMultisample(); - var format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); - var usage = TextureStorage.GetImageUsage(info.Format, info.Target, gd.Capabilities, isMsImageStorageSupported) & storage.UsageFlags; + VkFormat format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); + ImageUsageFlags usage = TextureStorage.GetImageUsage(info.Format, info.Target, gd.Capabilities, isMsImageStorageSupported) & storage.UsageFlags; - var levels = (uint)info.Levels; - var layers = (uint)info.GetLayers(); + uint levels = (uint)info.Levels; + uint layers = (uint)info.GetLayers(); VkFormat = format; - var type = info.Target.ConvertView(); + ImageViewType type = info.Target.ConvertView(); - var swizzleR = info.SwizzleR.Convert(); - var swizzleG = info.SwizzleG.Convert(); - var swizzleB = info.SwizzleB.Convert(); - var swizzleA = info.SwizzleA.Convert(); + ComponentSwizzle swizzleR = info.SwizzleR.Convert(); + ComponentSwizzle swizzleG = info.SwizzleG.Convert(); + ComponentSwizzle swizzleB = info.SwizzleB.Convert(); + ComponentSwizzle swizzleA = info.SwizzleA.Convert(); if (info.Format is Format.R5G5B5A1Unorm or Format.R5G5B5X1Unorm or Format.R5G6B5Unorm) { @@ -84,8 +84,8 @@ namespace Ryujinx.Graphics.Vulkan } else if (VkFormat == VkFormat.R4G4B4A4UnormPack16 || info.Format == Format.A1B5G5R5Unorm) { - var tempB = swizzleB; - var tempA = swizzleA; + ComponentSwizzle tempB = swizzleB; + ComponentSwizzle tempA = swizzleA; swizzleB = swizzleG; swizzleA = swizzleR; @@ -93,23 +93,23 @@ namespace Ryujinx.Graphics.Vulkan swizzleG = tempB; } - var componentMapping = new ComponentMapping(swizzleR, swizzleG, swizzleB, swizzleA); + ComponentMapping componentMapping = new(swizzleR, swizzleG, swizzleB, swizzleA); - var aspectFlags = info.Format.ConvertAspectFlags(info.DepthStencilMode); - var aspectFlagsDepth = info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = info.Format.ConvertAspectFlags(info.DepthStencilMode); + ImageAspectFlags aspectFlagsDepth = info.Format.ConvertAspectFlags(); - var subresourceRange = new ImageSubresourceRange(aspectFlags, (uint)firstLevel, levels, (uint)firstLayer, layers); - var subresourceRangeDepth = new ImageSubresourceRange(aspectFlagsDepth, (uint)firstLevel, levels, (uint)firstLayer, layers); + ImageSubresourceRange subresourceRange = new(aspectFlags, (uint)firstLevel, levels, (uint)firstLayer, layers); + ImageSubresourceRange subresourceRangeDepth = new(aspectFlagsDepth, (uint)firstLevel, levels, (uint)firstLayer, layers); unsafe Auto CreateImageView(ComponentMapping cm, ImageSubresourceRange sr, ImageViewType viewType, ImageUsageFlags usageFlags) { - var imageViewUsage = new ImageViewUsageCreateInfo + ImageViewUsageCreateInfo imageViewUsage = new() { SType = StructureType.ImageViewUsageCreateInfo, Usage = usageFlags, }; - var imageCreateInfo = new ImageViewCreateInfo + ImageViewCreateInfo imageCreateInfo = new() { SType = StructureType.ImageViewCreateInfo, Image = storage.GetImageForViewCreation(), @@ -120,7 +120,7 @@ namespace Ryujinx.Graphics.Vulkan PNext = &imageViewUsage, }; - gd.Api.CreateImageView(device, in imageCreateInfo, null, out var imageView).ThrowOnError(); + gd.Api.CreateImageView(device, in imageCreateInfo, null, out ImageView* imageView).ThrowOnError(); return new Auto(new DisposableImageView(gd.Api, device, imageView), null, storage.GetImage()); } @@ -136,7 +136,7 @@ namespace Ryujinx.Graphics.Vulkan _imageView = CreateImageView(componentMapping, subresourceRange, type, shaderUsage); // Framebuffer attachments and storage images requires a identity component mapping. - var identityComponentMapping = new ComponentMapping( + ComponentMapping identityComponentMapping = new( ComponentSwizzle.R, ComponentSwizzle.G, ComponentSwizzle.B, @@ -210,8 +210,8 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, int firstLayer, int firstLevel) { - var src = this; - var dst = (TextureView)destination; + TextureView src = this; + TextureView dst = (TextureView)destination; if (!Valid || !dst.Valid) { @@ -220,10 +220,10 @@ namespace Ryujinx.Graphics.Vulkan _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; - var srcImage = src.GetImage().Get(cbs).Value; - var dstImage = dst.GetImage().Get(cbs).Value; + Image srcImage = src.GetImage().Get(cbs).Value; + Image dstImage = dst.GetImage().Get(cbs).Value; if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -272,8 +272,8 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, int srcLayer, int dstLayer, int srcLevel, int dstLevel) { - var src = this; - var dst = (TextureView)destination; + TextureView src = this; + TextureView dst = (TextureView)destination; if (!Valid || !dst.Valid) { @@ -282,10 +282,10 @@ namespace Ryujinx.Graphics.Vulkan _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; - var srcImage = src.GetImage().Get(cbs).Value; - var dstImage = dst.GetImage().Get(cbs).Value; + Image srcImage = src.GetImage().Get(cbs).Value; + Image dstImage = dst.GetImage().Get(cbs).Value; if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -329,21 +329,21 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter) { - var dst = (TextureView)destination; + TextureView dst = (TextureView)destination; if (_gd.CommandBufferPool.OwnedByCurrentThread) { _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; CopyToImpl(cbs, dst, srcRegion, dstRegion, linearFilter); } else { - var cbp = _gd.BackgroundResources.Get().GetPool(); + CommandBufferPool cbp = _gd.BackgroundResources.Get().GetPool(); - using var cbs = cbp.Rent(); + using CommandBufferScoped cbs = cbp.Rent(); CopyToImpl(cbs, dst, srcRegion, dstRegion, linearFilter); } @@ -351,10 +351,10 @@ namespace Ryujinx.Graphics.Vulkan private void CopyToImpl(CommandBufferScoped cbs, TextureView dst, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter) { - var src = this; + TextureView src = this; - var srcFormat = GetCompatibleGalFormat(src.Info.Format); - var dstFormat = GetCompatibleGalFormat(dst.Info.Format); + Format srcFormat = GetCompatibleGalFormat(src.Info.Format); + Format dstFormat = GetCompatibleGalFormat(dst.Info.Format); bool srcUsesStorageFormat = src.VkFormat == src.Storage.VkFormat; bool dstUsesStorageFormat = dst.VkFormat == dst.Storage.VkFormat; @@ -582,7 +582,7 @@ namespace Ryujinx.Graphics.Vulkan return this; } - if (_selfManagedViews != null && _selfManagedViews.TryGetValue(format, out var view)) + if (_selfManagedViews != null && _selfManagedViews.TryGetValue(format, out TextureView view)) { return view; } @@ -622,12 +622,12 @@ namespace Ryujinx.Graphics.Vulkan public byte[] GetData(int x, int y, int width, int height) { int size = width * height * Info.BytesPerPixel; - using var bufferHolder = _gd.BufferManager.Create(_gd, size); + using BufferHolder bufferHolder = _gd.BufferManager.Create(_gd, size); - using (var cbs = _gd.CommandBufferPool.Rent()) + using (CommandBufferScoped cbs = _gd.CommandBufferPool.Rent()) { - var buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = GetImage().Get(cbs).Value; + VkBuffer buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = GetImage().Get(cbs).Value; CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, 0, 0, x, y, width, height); } @@ -669,12 +669,12 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(BufferRange range, int layer, int level, int stride) { _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; int outSize = Info.GetMipSize(level); int hostSize = GetBufferDataLength(outSize); - var image = GetImage().Get(cbs).Value; + Image image = GetImage().Get(cbs).Value; int offset = range.Offset; Auto autoBuffer = _gd.BufferManager.GetBuffer(cbs.CommandBuffer, range.Handle, true); @@ -783,7 +783,7 @@ namespace Ryujinx.Graphics.Vulkan { int bufferDataLength = GetBufferDataLength(data.Length); - using var bufferHolder = _gd.BufferManager.Create(_gd, bufferDataLength); + using BufferHolder bufferHolder = _gd.BufferManager.Create(_gd, bufferDataLength); Auto imageAuto = GetImage(); @@ -791,7 +791,7 @@ namespace Ryujinx.Graphics.Vulkan bool loadInline = Storage.HasCommandBufferDependency(_gd.PipelineInternal.CurrentCommandBuffer); - var cbs = loadInline ? _gd.PipelineInternal.CurrentCommandBuffer : _gd.PipelineInternal.GetPreloadCommandBuffer(); + CommandBufferScoped cbs = loadInline ? _gd.PipelineInternal.CurrentCommandBuffer : _gd.PipelineInternal.GetPreloadCommandBuffer(); if (loadInline) { @@ -800,8 +800,8 @@ namespace Ryujinx.Graphics.Vulkan CopyDataToBuffer(bufferHolder.GetDataStorage(0, bufferDataLength), data); - var buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = imageAuto.Get(cbs).Value; + VkBuffer buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = imageAuto.Get(cbs).Value; if (region.HasValue) { @@ -937,24 +937,24 @@ namespace Ryujinx.Graphics.Vulkan int rowLength = ((stride == 0 ? Info.GetMipStride(dstLevel + level) : stride) / Info.BytesPerPixel) * Info.BlockWidth; - var aspectFlags = Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = Info.Format.ConvertAspectFlags(); if (aspectFlags == (ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit)) { aspectFlags = ImageAspectFlags.DepthBit; } - var sl = new ImageSubresourceLayers( + ImageSubresourceLayers sl = new( aspectFlags, (uint)(FirstLevel + dstLevel + level), (uint)(FirstLayer + layer), (uint)layers); - var extent = new Extent3D((uint)width, (uint)height, (uint)depth); + Extent3D extent = new((uint)width, (uint)height, (uint)depth); int z = is3D ? dstLayer : 0; - var region = new BufferImageCopy( + BufferImageCopy region = new( (ulong)offset, (uint)AlignUpNpot(rowLength, Info.BlockWidth), (uint)AlignUpNpot(height, Info.BlockHeight), @@ -996,16 +996,16 @@ namespace Ryujinx.Graphics.Vulkan int width, int height) { - var aspectFlags = Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = Info.Format.ConvertAspectFlags(); if (aspectFlags == (ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit)) { aspectFlags = ImageAspectFlags.DepthBit; } - var sl = new ImageSubresourceLayers(aspectFlags, (uint)(FirstLevel + dstLevel), (uint)(FirstLayer + dstLayer), 1); + ImageSubresourceLayers sl = new(aspectFlags, (uint)(FirstLevel + dstLevel), (uint)(FirstLayer + dstLayer), 1); - var extent = new Extent3D((uint)width, (uint)height, 1); + Extent3D extent = new((uint)width, (uint)height, 1); int rowLengthAlignment = Info.BlockWidth; @@ -1015,7 +1015,7 @@ namespace Ryujinx.Graphics.Vulkan rowLengthAlignment = 4 / Info.BytesPerPixel; } - var region = new BufferImageCopy( + BufferImageCopy region = new( 0, (uint)AlignUpNpot(width, rowLengthAlignment), (uint)AlignUpNpot(height, Info.BlockHeight), @@ -1083,7 +1083,7 @@ namespace Ryujinx.Graphics.Vulkan CommandBufferScoped cbs, FramebufferParams fb) { - var key = fb.GetRenderPassCacheKey(); + RenderPassCacheKey key = fb.GetRenderPassCacheKey(); if (_renderPasses == null || !_renderPasses.TryGetValue(ref key, out RenderPassHolder rpHolder)) { @@ -1131,9 +1131,9 @@ namespace Ryujinx.Graphics.Vulkan if (_renderPasses != null) { - var renderPasses = _renderPasses.Values.ToArray(); + RenderPassHolder[] renderPasses = _renderPasses.Values.ToArray(); - foreach (var pass in renderPasses) + foreach (RenderPassHolder pass in renderPasses) { pass.Dispose(); } @@ -1141,7 +1141,7 @@ namespace Ryujinx.Graphics.Vulkan if (_selfManagedViews != null) { - foreach (var view in _selfManagedViews.Values) + foreach (TextureView view in _selfManagedViews.Values) { view.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs index f4d512f92..85500f305 100644 --- a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs @@ -1,4 +1,5 @@ using Ryujinx.Graphics.GAL; +using Silk.NET.Vulkan; namespace Ryujinx.Graphics.Vulkan { @@ -50,7 +51,7 @@ namespace Ryujinx.Graphics.Vulkan public void BindVertexBuffer(VulkanRenderer gd, CommandBufferScoped cbs, uint binding, ref PipelineState state, VertexBufferUpdater updater) { - var autoBuffer = _buffer; + Auto autoBuffer = _buffer; if (_handle != BufferHandle.Null) { @@ -67,7 +68,7 @@ namespace Ryujinx.Graphics.Vulkan int stride = (_stride + (alignment - 1)) & -alignment; int newSize = (_size / _stride) * stride; - var buffer = autoBuffer.Get(cbs, 0, newSize).Value; + Buffer buffer = autoBuffer.Get(cbs, 0, newSize).Value; updater.BindVertexBuffer(cbs, binding, buffer, 0, (ulong)newSize, (ulong)stride); @@ -94,7 +95,7 @@ namespace Ryujinx.Graphics.Vulkan { int offset = _offset; bool mirrorable = _size <= VertexBufferMaxMirrorable; - var buffer = mirrorable ? autoBuffer.GetMirrorable(cbs, ref offset, _size, out _).Value : autoBuffer.Get(cbs, offset, _size).Value; + Buffer buffer = mirrorable ? autoBuffer.GetMirrorable(cbs, ref offset, _size, out _).Value : autoBuffer.Get(cbs, offset, _size).Value; updater.BindVertexBuffer(cbs, binding, buffer, (ulong)offset, (ulong)_size, (ulong)_stride); } diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs index 4631f920a..d133a7ea1 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs @@ -64,7 +64,7 @@ namespace Ryujinx.Graphics.Vulkan _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\"."), }; - var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT + DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfo = new() { SType = StructureType.DebugUtilsMessengerCreateInfoExt, MessageType = messageType, @@ -98,7 +98,7 @@ namespace Ryujinx.Graphics.Vulkan DebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { - var msg = Marshal.PtrToStringAnsi((nint)pCallbackData->PMessage); + string msg = Marshal.PtrToStringAnsi((nint)pCallbackData->PMessage); if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)) { diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs index da02c2489..95810a4e1 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs @@ -4,6 +4,7 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using Silk.NET.Vulkan.Extensions.EXT; using Silk.NET.Vulkan.Extensions.KHR; +using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; @@ -57,10 +58,10 @@ namespace Ryujinx.Graphics.Vulkan internal static VulkanInstance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions) { - var enabledLayers = new List(); + List enabledLayers = new(); - var instanceExtensions = VulkanInstance.GetInstanceExtensions(api); - var instanceLayers = VulkanInstance.GetInstanceLayers(api); + IReadOnlySet instanceExtensions = VulkanInstance.GetInstanceExtensions(api); + IReadOnlySet instanceLayers = VulkanInstance.GetInstanceLayers(api); void AddAvailableLayer(string layerName) { @@ -79,16 +80,16 @@ namespace Ryujinx.Graphics.Vulkan AddAvailableLayer("VK_LAYER_KHRONOS_validation"); } - var enabledExtensions = requiredExtensions; + string[] enabledExtensions = requiredExtensions; if (instanceExtensions.Contains("VK_EXT_debug_utils")) { enabledExtensions = enabledExtensions.Append(ExtDebugUtils.ExtensionName).ToArray(); } - var appName = Marshal.StringToHGlobalAnsi(AppName); + IntPtr appName = Marshal.StringToHGlobalAnsi(AppName); - var applicationInfo = new ApplicationInfo + ApplicationInfo applicationInfo = new() { PApplicationName = (byte*)appName, ApplicationVersion = 1, @@ -110,7 +111,7 @@ namespace Ryujinx.Graphics.Vulkan ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]); } - var instanceCreateInfo = new InstanceCreateInfo + InstanceCreateInfo instanceCreateInfo = new() { SType = StructureType.InstanceCreateInfo, PApplicationInfo = &applicationInfo, @@ -120,7 +121,7 @@ namespace Ryujinx.Graphics.Vulkan EnabledLayerCount = (uint)enabledLayers.Count, }; - Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var instance); + Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out VulkanInstance instance); Marshal.FreeHGlobal(appName); @@ -141,7 +142,7 @@ namespace Ryujinx.Graphics.Vulkan internal static VulkanPhysicalDevice FindSuitablePhysicalDevice(Vk api, VulkanInstance instance, SurfaceKHR surface, string preferredGpuId) { - instance.EnumeratePhysicalDevices(out var physicalDevices).ThrowOnError(); + instance.EnumeratePhysicalDevices(out VulkanPhysicalDevice[] physicalDevices).ThrowOnError(); // First we try to pick the user preferred GPU. for (int i = 0; i < physicalDevices.Length; i++) @@ -166,9 +167,9 @@ namespace Ryujinx.Graphics.Vulkan internal static DeviceInfo[] GetSuitablePhysicalDevices(Vk api) { - var appName = Marshal.StringToHGlobalAnsi(AppName); + IntPtr appName = Marshal.StringToHGlobalAnsi(AppName); - var applicationInfo = new ApplicationInfo + ApplicationInfo applicationInfo = new() { PApplicationName = (byte*)appName, ApplicationVersion = 1, @@ -177,7 +178,7 @@ namespace Ryujinx.Graphics.Vulkan ApiVersion = _maximumVulkanVersion, }; - var instanceCreateInfo = new InstanceCreateInfo + InstanceCreateInfo instanceCreateInfo = new() { SType = StructureType.InstanceCreateInfo, PApplicationInfo = &applicationInfo, @@ -187,7 +188,7 @@ namespace Ryujinx.Graphics.Vulkan EnabledLayerCount = 0, }; - Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var rawInstance); + Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out VulkanInstance rawInstance); Marshal.FreeHGlobal(appName); @@ -248,13 +249,13 @@ namespace Ryujinx.Graphics.Vulkan { const QueueFlags RequiredFlags = QueueFlags.GraphicsBit | QueueFlags.ComputeBit; - var khrSurface = new KhrSurface(api.Context); + KhrSurface khrSurface = new KhrSurface(api.Context); for (uint index = 0; index < physicalDevice.QueueFamilyProperties.Length; index++) { ref QueueFamilyProperties property = ref physicalDevice.QueueFamilyProperties[index]; - khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice.PhysicalDevice, index, surface, out var surfaceSupported).ThrowOnError(); + khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice.PhysicalDevice, index, surface, out Bool32 surfaceSupported).ThrowOnError(); if (property.QueueFlags.HasFlag(RequiredFlags) && surfaceSupported) { @@ -283,7 +284,7 @@ namespace Ryujinx.Graphics.Vulkan queuePriorities[i] = 1f; } - var queueCreateInfo = new DeviceQueueCreateInfo + DeviceQueueCreateInfo queueCreateInfo = new() { SType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = queueFamilyIndex, @@ -493,9 +494,9 @@ namespace Ryujinx.Graphics.Vulkan api.GetPhysicalDeviceFeatures2(physicalDevice.PhysicalDevice, &features2); - var supportedFeatures = features2.Features; + PhysicalDeviceFeatures supportedFeatures = features2.Features; - var features = new PhysicalDeviceFeatures + PhysicalDeviceFeatures features = new() { DepthBiasClamp = supportedFeatures.DepthBiasClamp, DepthClamp = supportedFeatures.DepthClamp, @@ -574,7 +575,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresExtendedDynamicState; - var featuresVk11 = new PhysicalDeviceVulkan11Features + PhysicalDeviceVulkan11Features featuresVk11 = new() { SType = StructureType.PhysicalDeviceVulkan11Features, PNext = pExtendedFeatures, @@ -587,7 +588,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresVk11; - var featuresVk12 = new PhysicalDeviceVulkan12Features + PhysicalDeviceVulkan12Features featuresVk12 = new() { SType = StructureType.PhysicalDeviceVulkan12Features, PNext = pExtendedFeatures, @@ -683,7 +684,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresDeviceMemoryPriority; } - var enabledExtensions = _requiredExtensions.Union(_desirableExtensions.Intersect(physicalDevice.DeviceExtensions)).ToArray(); + string[] enabledExtensions = _requiredExtensions.Union(_desirableExtensions.Intersect(physicalDevice.DeviceExtensions)).ToArray(); nint* ppEnabledExtensions = stackalloc nint[enabledExtensions.Length]; @@ -692,7 +693,7 @@ namespace Ryujinx.Graphics.Vulkan ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]); } - var deviceCreateInfo = new DeviceCreateInfo + DeviceCreateInfo deviceCreateInfo = new() { SType = StructureType.DeviceCreateInfo, PNext = pExtendedFeatures, @@ -703,7 +704,7 @@ namespace Ryujinx.Graphics.Vulkan PEnabledFeatures = &features, }; - api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError(); + api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out Device* device).ThrowOnError(); for (int i = 0; i < enabledExtensions.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs b/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs index b3f8fd756..8ede84100 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs @@ -24,7 +24,7 @@ namespace Ryujinx.Graphics.Vulkan PhysicalDevice = physicalDevice; PhysicalDeviceFeatures = api.GetPhysicalDeviceFeature(PhysicalDevice); - api.GetPhysicalDeviceProperties(PhysicalDevice, out var physicalDeviceProperties); + api.GetPhysicalDeviceProperties(PhysicalDevice, out PhysicalDeviceProperties physicalDeviceProperties); PhysicalDeviceProperties = physicalDeviceProperties; api.GetPhysicalDeviceMemoryProperties(PhysicalDevice, out PhysicalDeviceMemoryProperties); diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs index 4a4524eaa..69c6dc5c4 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs @@ -11,6 +11,7 @@ using Silk.NET.Vulkan.Extensions.KHR; using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; using System.Threading; using Format = Ryujinx.Graphics.GAL.Format; using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; @@ -173,7 +174,7 @@ namespace Ryujinx.Graphics.Vulkan if (maxQueueCount >= 2) { - Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue); + Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out Queue backgroundQueue); BackgroundQueue = backgroundQueue; BackgroundQueueLock = new(); } @@ -341,7 +342,7 @@ namespace Ryujinx.Graphics.Vulkan Api.GetPhysicalDeviceProperties2(_physicalDevice.PhysicalDevice, &properties2); Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2); - var portabilityFlags = PortabilitySubsetFlags.None; + PortabilitySubsetFlags portabilityFlags = PortabilitySubsetFlags.None; uint vertexBufferAlignment = 1; if (usePortability) @@ -358,9 +359,9 @@ namespace Ryujinx.Graphics.Vulkan featuresCustomBorderColor.CustomBorderColors && featuresCustomBorderColor.CustomBorderColorWithoutFormat; - ref var properties = ref properties2.Properties; + ref PhysicalDeviceProperties properties = ref properties2.Properties; - var hasDriverProperties = _physicalDevice.TryGetPhysicalDeviceDriverPropertiesKHR(Api, out var driverProperties); + bool hasDriverProperties = _physicalDevice.TryGetPhysicalDeviceDriverPropertiesKHR(Api, out PhysicalDeviceDriverPropertiesKHR driverProperties); Vendor = VendorUtils.FromId(properties.VendorID); @@ -394,7 +395,7 @@ namespace Ryujinx.Graphics.Vulkan if (Vendor == Vendor.Nvidia) { - var match = VendorUtils.NvidiaConsumerClassRegex().Match(GpuRenderer); + Match match = VendorUtils.NvidiaConsumerClassRegex().Match(GpuRenderer); if (match != null && int.TryParse(match.Groups[2].Value, out int gpuNumber)) { @@ -504,7 +505,7 @@ namespace Ryujinx.Graphics.Vulkan _surface = _getSurface(_instance.Instance, Api); _physicalDevice = VulkanInitialization.FindSuitablePhysicalDevice(Api, _instance, _surface, _preferredGpuId); - var queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(Api, _physicalDevice, _surface, out uint maxQueueCount); + uint queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(Api, _physicalDevice, _surface, out uint maxQueueCount); _device = VulkanInitialization.CreateDevice(Api, _physicalDevice, queueFamilyIndex, maxQueueCount); @@ -513,7 +514,7 @@ namespace Ryujinx.Graphics.Vulkan SwapchainApi = swapchainApi; } - Api.GetDeviceQueue(_device, queueFamilyIndex, 0, out var queue); + Api.GetDeviceQueue(_device, queueFamilyIndex, 0, out Queue queue); Queue = queue; QueueLock = new(); @@ -521,7 +522,7 @@ namespace Ryujinx.Graphics.Vulkan SurfaceLock = new(); if (maxQueueCount >= 2) { - Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue); + Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out Queue backgroundQueue); BackgroundQueue = backgroundQueue; BackgroundQueueLock = new(); } @@ -616,7 +617,7 @@ namespace Ryujinx.Graphics.Vulkan internal TextureView CreateTextureView(TextureCreateInfo info) { // This should be disposed when all views are destroyed. - var storage = CreateTextureStorage(info); + TextureStorage storage = CreateTextureStorage(info); return storage.CreateView(info, 0, 0); } @@ -739,8 +740,8 @@ namespace Ryujinx.Graphics.Vulkan Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2); - var limits = _physicalDevice.PhysicalDeviceProperties.Limits; - var mainQueueProperties = _physicalDevice.QueueFamilyProperties[QueueFamilyIndex]; + PhysicalDeviceLimits limits = _physicalDevice.PhysicalDeviceProperties.Limits; + QueueFamilyProperties mainQueueProperties = _physicalDevice.QueueFamilyProperties[QueueFamilyIndex]; SystemMemoryType memoryType; @@ -1181,9 +1182,9 @@ namespace Ryujinx.Graphics.Vulkan MemoryAllocator.Dispose(); - foreach (var shader in Shaders) shader.Dispose(); - foreach (var texture in Textures) texture.Release(); - foreach (var sampler in Samplers) sampler.Dispose(); + foreach (ShaderCollection shader in Shaders) shader.Dispose(); + foreach (ITexture texture in Textures) texture.Release(); + foreach (SamplerHolder sampler in Samplers) sampler.Dispose(); if (_surface.Handle != 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/Window.cs b/src/Ryujinx.Graphics.Vulkan/Window.cs index eca7580e4..9aaa89417 100644 --- a/src/Ryujinx.Graphics.Vulkan/Window.cs +++ b/src/Ryujinx.Graphics.Vulkan/Window.cs @@ -70,7 +70,7 @@ namespace Ryujinx.Graphics.Vulkan { caps = default; if (!CanQuerySurface()) return false; - var res = _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out caps); + Result res = _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out caps); return res == Result.Success; } @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Vulkan if (!CanQuerySurface()) return false; uint count = 0; - var res = _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &count, null); + Result res = _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &count, null); if (res != Result.Success || count == 0) return false; formats = new SurfaceFormatKHR[count]; @@ -98,7 +98,7 @@ namespace Ryujinx.Graphics.Vulkan if (!CanQuerySurface()) return false; uint count = 0; - var res = _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &count, null); + Result res = _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &count, null); if (res != Result.Success || count == 0) return false; modes = new PresentModeKHR[count]; @@ -120,7 +120,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_gd.SurfaceLock) { - var oldSwapchain = _swapchain; + SwapchainKHR oldSwapchain = _swapchain; _swapchainIsDirty = false; if (_swapchainImageViews != null) @@ -194,19 +194,19 @@ namespace Ryujinx.Graphics.Vulkan lock (_gd.SurfaceLock) { - if (!TryGetSurfaceCapabilities(out var capabilities)) + if (!TryGetSurfaceCapabilities(out SurfaceCapabilitiesKHR capabilities)) { _swapchainIsDirty = true; return; } - if (!TryGetSurfaceFormats(out var surfaceFormats)) + if (!TryGetSurfaceFormats(out SurfaceFormatKHR[] surfaceFormats)) { _swapchainIsDirty = true; return; } - if (!TryGetPresentModes(out var presentModes)) + if (!TryGetPresentModes(out PresentModeKHR[] presentModes)) { _swapchainIsDirty = true; return; @@ -218,8 +218,8 @@ namespace Ryujinx.Graphics.Vulkan imageCount = capabilities.MaxImageCount; } - var surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats, _colorSpacePassthroughEnabled); - var extent = ChooseSwapExtent(capabilities); + SurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats, _colorSpacePassthroughEnabled); + Extent2D extent = ChooseSwapExtent(capabilities); // Guard against 0x0 extent immediately after resume if (extent.Width == 0 || extent.Height == 0) @@ -232,7 +232,7 @@ namespace Ryujinx.Graphics.Vulkan _height = (int)extent.Height; _format = surfaceFormat.Format; - var oldSwapchain = _swapchain; + SwapchainKHR oldSwapchain = _swapchain; CurrentTransform = capabilities.CurrentTransform; @@ -243,11 +243,11 @@ namespace Ryujinx.Graphics.Vulkan } // On Android: Identity; otherwise, the CurrentTransform recommended by the driver - var preTransform = PlatformInfo.IsBionic + SurfaceTransformFlagsKHR preTransform = PlatformInfo.IsBionic ? SurfaceTransformFlagsKHR.IdentityBitKhr : capabilities.CurrentTransform; - var swapchainCreateInfo = new SwapchainCreateInfoKHR + SwapchainCreateInfoKHR swapchainCreateInfo = new() { SType = StructureType.SwapchainCreateInfoKhr, Surface = _surface, @@ -264,7 +264,7 @@ namespace Ryujinx.Graphics.Vulkan Clipped = true, }; - var textureCreateInfo = new TextureCreateInfo( + TextureCreateInfo textureCreateInfo = new( _width, _height, 1, @@ -299,7 +299,7 @@ namespace Ryujinx.Graphics.Vulkan _swapchainImageViews[i] = CreateSwapchainImageView(_swapchainImages[i], surfaceFormat.Format, textureCreateInfo); } - var semaphoreCreateInfo = new SemaphoreCreateInfo + SemaphoreCreateInfo semaphoreCreateInfo = new() { SType = StructureType.SemaphoreCreateInfo, }; @@ -322,7 +322,7 @@ namespace Ryujinx.Graphics.Vulkan private unsafe TextureView CreateSwapchainImageView(Image swapchainImage, VkFormat format, TextureCreateInfo info) { - var componentMapping = new ComponentMapping( + ComponentMapping componentMapping = new( ComponentSwizzle.R, ComponentSwizzle.G, ComponentSwizzle.B, @@ -330,9 +330,9 @@ namespace Ryujinx.Graphics.Vulkan var aspectFlags = ImageAspectFlags.ColorBit; - var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1); + ImageSubresourceRange subresourceRange = new(aspectFlags, 0, 1, 0, 1); - var imageCreateInfo = new ImageViewCreateInfo + ImageViewCreateInfo imageCreateInfo = new() { SType = StructureType.ImageViewCreateInfo, Image = swapchainImage, @@ -342,7 +342,7 @@ namespace Ryujinx.Graphics.Vulkan SubresourceRange = subresourceRange, }; - _gd.Api.CreateImageView(_device, in imageCreateInfo, null, out var imageView).ThrowOnError(); + _gd.Api.CreateImageView(_device, in imageCreateInfo, null, out ImageView* imageView).ThrowOnError(); return new TextureView(_gd, _device, new DisposableImageView(_gd.Api, _device, imageView), info, format); } @@ -359,7 +359,7 @@ namespace Ryujinx.Graphics.Vulkan return new SurfaceFormatKHR(VkFormat.B8G8R8A8Unorm, availableFormats[0].ColorSpace); } - foreach (var f in availableFormats) + foreach (SurfaceFormatKHR f in availableFormats) { if (f.Format == VkFormat.B8G8R8A8Unorm) { @@ -449,7 +449,7 @@ namespace Ryujinx.Graphics.Vulkan while (true) { - var acquireResult = _gd.SwapchainApi.AcquireNextImage( + Result acquireResult = _gd.SwapchainApi.AcquireNextImage( _device, _swapchain, ulong.MaxValue, @@ -485,11 +485,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var swapchainImage = _swapchainImages[nextImage]; + Image swapchainImage = _swapchainImages[nextImage]; _gd.FlushAllCommands(); - var cbs = _gd.CommandBufferPool.Rent(); + CommandBufferScoped cbs = _gd.CommandBufferPool.Rent(); // --- Set layout/stages correctly depending on the path --- bool allowStorageDst = !PlatformInfo.IsBionic; // Android: kein Storage auf Swapchain @@ -522,7 +522,7 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout.ColorAttachmentOptimal); } - var view = (TextureView)texture; + TextureView view = (TextureView)texture; UpdateEffect(); @@ -560,7 +560,7 @@ namespace Ryujinx.Graphics.Vulkan if (_effect != null) { _gd.FlushAllCommands(); - var emptySems = Array.Empty(); + Semaphore[] emptySems = Array.Empty(); var waitStagesCO = new[] { PipelineStageFlags.ColorAttachmentOutputBit }; _gd.CommandBufferPool.Return( cbs, @@ -642,9 +642,9 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout.PresentSrcKhr); } - var waitSems = new[] { _imageAvailableSemaphores[semaphoreIndex] }; + Semaphore[] waitSems = new[] { _imageAvailableSemaphores[semaphoreIndex] }; var waitStages = new[] { PipelineStageFlags.ColorAttachmentOutputBit }; // Important on Android - var signalSems = new[] { _renderFinishedSemaphores[semaphoreIndex] }; + Semaphore[] signalSems = new[] { _renderFinishedSemaphores[semaphoreIndex] }; _gd.CommandBufferPool.Return(cbs, waitSems, waitStages, signalSems); _gd.FlushAllCommands(); @@ -668,7 +668,7 @@ namespace Ryujinx.Graphics.Vulkan pSwap[0] = swapchain; pImageIndex[0] = imageIndex; - var presentInfo = new PresentInfoKHR + PresentInfoKHR presentInfo = new() { SType = StructureType.PresentInfoKhr, WaitSemaphoreCount = 1, @@ -735,7 +735,7 @@ namespace Ryujinx.Graphics.Vulkan case AntiAliasing.SmaaMedium: case AntiAliasing.SmaaHigh: case AntiAliasing.SmaaUltra: - var quality = _currentAntiAliasing - AntiAliasing.SmaaLow; + int quality = _currentAntiAliasing - AntiAliasing.SmaaLow; if (_effect is SmaaPostProcessingEffect smaa) { smaa.Quality = quality; @@ -797,9 +797,9 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout srcLayout, ImageLayout dstLayout) { - var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1); + ImageSubresourceRange subresourceRange = new(ImageAspectFlags.ColorBit, 0, 1, 0, 1); - var barrier = new ImageMemoryBarrier + ImageMemoryBarrier barrier = new() { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = srcAccess, diff --git a/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs b/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs index 788877155..8a080bcfe 100644 --- a/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs +++ b/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs @@ -1,6 +1,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using System.Collections.Generic; using System.Linq; namespace Ryujinx.HLE.Generators @@ -10,7 +11,7 @@ namespace Ryujinx.HLE.Generators { public void Execute(GeneratorExecutionContext context) { - var syntaxReceiver = (ServiceSyntaxReceiver)context.SyntaxReceiver; + ServiceSyntaxReceiver syntaxReceiver = (ServiceSyntaxReceiver)context.SyntaxReceiver; CodeGenerator generator = new(); generator.AppendLine("#nullable enable"); @@ -21,16 +22,16 @@ namespace Ryujinx.HLE.Generators generator.EnterScope($"public IpcService? GetServiceInstance(Type type, ServiceCtx context, object? parameter = null)"); if (syntaxReceiver != null) { - foreach (var className in syntaxReceiver.Types) + foreach (ClassDeclarationSyntax className in syntaxReceiver.Types) { if (className.Modifiers.Any(SyntaxKind.AbstractKeyword) || className.Modifiers.Any(SyntaxKind.PrivateKeyword) || !className.AttributeLists.Any(x => x.Attributes.Any(y => y.ToString().StartsWith("Service")))) continue; - var name = GetFullName(className, context).Replace("global::", ""); + string name = GetFullName(className, context).Replace("global::", ""); if (!name.StartsWith("Ryujinx.HLE.HOS.Services")) continue; - var constructors = className.ChildNodes().Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration)) + IEnumerable constructors = className.ChildNodes().Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration)) .Select(y => y as ConstructorDeclarationSyntax); if (!constructors.Any(x => x?.ParameterList.Parameters.Count >= 1)) @@ -42,14 +43,14 @@ namespace Ryujinx.HLE.Generators generator.EnterScope($"if (type == typeof({GetFullName(className, context)}))"); if (constructors.Any(x => x?.ParameterList.Parameters.Count == 2)) { - var type = constructors + TypeSyntax type = constructors .FirstOrDefault(x => x?.ParameterList.Parameters.Count == 2).ParameterList .Parameters[1].Type; if (type?.SyntaxTree != null) { var model = context.Compilation.GetSemanticModel(type.SyntaxTree); - var typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol; - var fullName = typeSymbol?.ToString(); + INamedTypeSymbol typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol; + string fullName = typeSymbol?.ToString(); generator.EnterScope("if (parameter != null)"); generator.AppendLine($"return new {GetFullName(className, context)}(context, ({fullName})parameter);"); } diff --git a/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs b/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs index ac260d196..a7cce697a 100644 --- a/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs +++ b/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs @@ -3,6 +3,7 @@ using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.HOS.Services; using System; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; @@ -52,12 +53,12 @@ namespace Ryujinx.HLE.Exceptions if (callingType != null && callingMethod != null) { // If the type is past 0xF, we are using TIPC - var ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands; + IReadOnlyDictionary ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands; // Find the handler for the method called - var ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod); - var ipcCommandId = ipcHandler.Key; - var ipcMethod = ipcHandler.Value; + KeyValuePair ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod); + int ipcCommandId = ipcHandler.Key; + MethodInfo ipcMethod = ipcHandler.Value; if (ipcMethod != null) { @@ -82,7 +83,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tPtrBuff:"); - foreach (var buff in Request.PtrBuff) + foreach (IpcPtrBuffDesc buff in Request.PtrBuff) { sb.AppendLine($"\t[{buff.Index}] Position: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); } @@ -92,7 +93,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tSendBuff:"); - foreach (var buff in Request.SendBuff) + foreach (IpcBuffDesc buff in Request.SendBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -102,7 +103,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tReceiveBuff:"); - foreach (var buff in Request.ReceiveBuff) + foreach (IpcBuffDesc buff in Request.ReceiveBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -112,7 +113,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tExchangeBuff:"); - foreach (var buff in Request.ExchangeBuff) + foreach (IpcBuffDesc buff in Request.ExchangeBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -122,7 +123,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tRecvListBuff:"); - foreach (var buff in Request.RecvListBuff) + foreach (IpcRecvListBuffDesc buff in Request.RecvListBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); } @@ -146,8 +147,8 @@ namespace Ryujinx.HLE.Exceptions // Find the IIpcService method that threw this exception while ((frame = trace.GetFrame(i++)) != null) { - var method = frame.GetMethod(); - var declType = method?.DeclaringType; + MethodBase method = frame.GetMethod(); + Type declType = method?.DeclaringType; if (typeof(IpcService).IsAssignableFrom(declType)) { diff --git a/src/Ryujinx.HLE/FileSystem/ContentManager.cs b/src/Ryujinx.HLE/FileSystem/ContentManager.cs index 66d432556..a99d2b4fe 100644 --- a/src/Ryujinx.HLE/FileSystem/ContentManager.cs +++ b/src/Ryujinx.HLE/FileSystem/ContentManager.cs @@ -107,15 +107,15 @@ namespace Ryujinx.HLE.FileSystem foreach (StorageId storageId in Enum.GetValues()) { - if (!ContentPath.TryGetContentPath(storageId, out var contentPathString)) + if (!ContentPath.TryGetContentPath(storageId, out string contentPathString)) { continue; } - if (!ContentPath.TryGetRealPath(contentPathString, out var contentDirectory)) + if (!ContentPath.TryGetRealPath(contentPathString, out string contentDirectory)) { continue; } - var registeredDirectory = Path.Combine(contentDirectory, "registered"); + string registeredDirectory = Path.Combine(contentDirectory, "registered"); Directory.CreateDirectory(registeredDirectory); @@ -170,7 +170,7 @@ namespace Ryujinx.HLE.FileSystem } } - if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0) + if (_locationEntries.TryGetValue(storageId, out LinkedList locationEntriesItem) && locationEntriesItem?.Count == 0) { _locationEntries.Remove(storageId); } @@ -200,7 +200,7 @@ namespace Ryujinx.HLE.FileSystem if (!mergedToContainer) { - using var pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem); + using IFileSystem pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem); } } } @@ -217,17 +217,17 @@ namespace Ryujinx.HLE.FileSystem if (AocData.TryGetValue(aocTitleId, out AocItem aoc)) { - var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read); - using var ncaFile = new UniqueRef(); + FileStream file = new(aoc.ContainerPath, FileMode.Open, FileAccess.Read); + using UniqueRef ncaFile = new(); switch (Path.GetExtension(aoc.ContainerPath)) { case ".xci": - var xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure); + XciPartition xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure); xci.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); break; case ".nsp": - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new(); pfs.Initialize(file.AsStorage()); pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); break; @@ -278,7 +278,7 @@ namespace Ryujinx.HLE.FileSystem { if (_contentDictionary.ContainsValue(ncaId)) { - var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); + KeyValuePair<(ulong titleId, NcaContentType type), string> content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); ulong titleId = content.Key.titleId; NcaContentType contentType = content.Key.type; @@ -295,7 +295,7 @@ namespace Ryujinx.HLE.FileSystem { lock (_lock) { - if (_contentDictionary.TryGetValue((titleId, contentType), out var contentDictionaryItem)) + if (_contentDictionary.TryGetValue((titleId, contentType), out string contentDictionaryItem)) { return UInt128Utils.FromHex(contentDictionaryItem); } @@ -430,8 +430,8 @@ namespace Ryujinx.HLE.FileSystem public void InstallFirmware(string firmwareSource) { - ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out var contentPathString); - ContentPath.TryGetRealPath(contentPathString, out var contentDirectory); + ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out string contentPathString); + ContentPath.TryGetRealPath(contentPathString, out string contentDirectory); string registeredDirectory = Path.Combine(contentDirectory, "registered"); string temporaryDirectory = Path.Combine(contentDirectory, "temp"); @@ -478,8 +478,8 @@ namespace Ryujinx.HLE.FileSystem public void InstallFirmware(Stream stream, bool isXci) { - ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out var contentPathString); - ContentPath.TryGetRealPath(contentPathString, out var contentDirectory); + ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out string contentPathString); + ContentPath.TryGetRealPath(contentPathString, out string contentDirectory); string registeredDirectory = Path.Combine(contentDirectory, "registered"); string temporaryDirectory = Path.Combine(contentDirectory, "temp"); @@ -501,7 +501,7 @@ namespace Ryujinx.HLE.FileSystem { if (Directory.Exists(keysSource)) { - foreach (var filePath in Directory.EnumerateFiles(keysSource, "*.keys")) + foreach (string filePath in Directory.EnumerateFiles(keysSource, "*.keys")) { VerifyKeysFile(filePath); File.Copy(filePath, Path.Combine(installDirectory, Path.GetFileName(filePath)), true); @@ -544,7 +544,7 @@ namespace Ryujinx.HLE.FileSystem Directory.Delete(temporaryDirectory, true); } Directory.CreateDirectory(temporaryDirectory); - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (Path.GetExtension(entry.FullName).Equals(".keys", StringComparison.OrdinalIgnoreCase)) { @@ -584,7 +584,7 @@ namespace Ryujinx.HLE.FileSystem private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory) { - foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) + foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca")) { Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage()); @@ -608,7 +608,7 @@ namespace Ryujinx.HLE.FileSystem private static void InstallFromZip(ZipArchive archive, string temporaryDirectory) { - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) { @@ -648,7 +648,7 @@ namespace Ryujinx.HLE.FileSystem private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode) { - using var file = new UniqueRef(); + using UniqueRef file = new(); if (filesystem.FileExists($"{path}/00")) { @@ -759,7 +759,7 @@ namespace Ryujinx.HLE.FileSystem Dictionary> updateNcas = new(); - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) { @@ -768,7 +768,7 @@ namespace Ryujinx.HLE.FileSystem Nca nca = new(_virtualFileSystem.KeySet, storage); - if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { updateNcasItem.Add((nca.Header.ContentType, entry.FullName)); } @@ -779,13 +779,13 @@ namespace Ryujinx.HLE.FileSystem } } - if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry)) + if (updateNcas.TryGetValue(SystemUpdateTitleId, out List<(NcaContentType type, string path)> ncaEntry)) { string metaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; CnmtContentMetaEntry[] metaEntries = null; - var fileEntry = archive.GetEntry(metaPath); + ZipArchiveEntry fileEntry = archive.GetEntry(metaPath); using (Stream ncaStream = GetZipStream(fileEntry)) { @@ -795,11 +795,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new(metaFile.Get.AsStream()); if (meta.Type == ContentMetaType.SystemUpdate) { @@ -815,16 +815,16 @@ namespace Ryujinx.HLE.FileSystem throw new FileNotFoundException("System update title was not found in the firmware package."); } - if (updateNcas.TryGetValue(SystemVersionTitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(SystemVersionTitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { string versionEntry = updateNcasItem.FirstOrDefault(x => x.type != NcaContentType.Meta).path; using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)); Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage()); - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -860,11 +860,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new(metaFile.Get.AsStream()); IStorage contentStorage = contentNcaStream.AsStorage(); if (contentStorage.GetSize(out long size).IsSuccess()) @@ -892,9 +892,9 @@ namespace Ryujinx.HLE.FileSystem { StringBuilder extraNcas = new(); - foreach (var entry in updateNcas) + foreach (KeyValuePair> entry in updateNcas) { - foreach (var (type, path) in entry.Value) + foreach ((NcaContentType type, string path) in entry.Value) { extraNcas.AppendLine(path); } @@ -919,7 +919,7 @@ namespace Ryujinx.HLE.FileSystem Dictionary> updateNcas = new(); - foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) + foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca")) { IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage(); @@ -931,11 +931,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new(metaFile.Get.AsStream()); if (meta.Type == ContentMetaType.SystemUpdate) { @@ -947,9 +947,9 @@ namespace Ryujinx.HLE.FileSystem } else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) { - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -957,7 +957,7 @@ namespace Ryujinx.HLE.FileSystem } } - if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { updateNcasItem.Add((nca.Header.ContentType, entry.FullPath)); } @@ -976,7 +976,7 @@ namespace Ryujinx.HLE.FileSystem foreach (CnmtContentMetaEntry metaEntry in metaEntries) { - if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry)) + if (updateNcas.TryGetValue(metaEntry.TitleId, out List<(NcaContentType type, string path)> ncaEntry)) { string metaNcaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; string contentPath = ncaEntry.FirstOrDefault(x => x.type != NcaContentType.Meta).path; @@ -999,11 +999,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new(metaFile.Get.AsStream()); if (contentStorage.GetSize(out long size).IsSuccess()) { @@ -1030,9 +1030,9 @@ namespace Ryujinx.HLE.FileSystem { StringBuilder extraNcas = new(); - foreach (var entry in updateNcas) + foreach (KeyValuePair> entry in updateNcas) { - foreach (var (type, path) in entry.Value) + foreach ((NcaContentType type, string path) in entry.Value) { extraNcas.AppendLine(path); } @@ -1050,22 +1050,22 @@ namespace Ryujinx.HLE.FileSystem lock (_lock) { - var locationEnties = _locationEntries[StorageId.BuiltInSystem]; + LinkedList locationEnties = _locationEntries[StorageId.BuiltInSystem]; - foreach (var entry in locationEnties) + foreach (LocationEntry entry in locationEnties) { if (entry.ContentType == NcaContentType.Data) { - var path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); + string path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); using FileStream fileStream = File.OpenRead(path); Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage()); if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) { - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -1132,7 +1132,7 @@ namespace Ryujinx.HLE.FileSystem public bool AreKeysAlredyPresent(string pathToCheck) { string[] fileNames = ["prod.keys", "title.keys", "console.keys", "dev.keys"]; - foreach (var file in fileNames) + foreach (string file in fileNames) { if (File.Exists(Path.Combine(pathToCheck, file))) { diff --git a/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs b/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs index 8cdb889be..a1f29bd13 100644 --- a/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs +++ b/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs @@ -39,7 +39,7 @@ namespace Ryujinx.HLE.FileSystem // TODO: Replace this with a check for IdOffset as soon as LibHac supports it: // && entry.IdOffset == programIndex - foreach (var entry in _cnmt.ContentEntries) + foreach (CnmtContentEntry entry in _cnmt.ContentEntries) { if (entry.Type != type) { diff --git a/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs b/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs index fd62f7102..655137804 100644 --- a/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs +++ b/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs @@ -61,7 +61,7 @@ namespace Ryujinx.HLE.FileSystem public void LoadRomFs(ulong pid, string fileName) { - var romfsStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + FileStream romfsStream = new(fileName, FileMode.Open, FileAccess.Read); _romFsByPid.AddOrUpdate(pid, romfsStream, (_, oldStream) => { @@ -140,8 +140,8 @@ namespace Ryujinx.HLE.FileSystem return $"{rawPath}:/"; } - var basePath = rawPath.AsSpan(0, firstSeparatorOffset); - var fileName = rawPath.AsSpan(firstSeparatorOffset + 1); + ReadOnlySpan basePath = rawPath.AsSpan(0, firstSeparatorOffset); + ReadOnlySpan fileName = rawPath.AsSpan(firstSeparatorOffset + 1); return $"{basePath}:/{fileName}"; } @@ -194,7 +194,7 @@ namespace Ryujinx.HLE.FileSystem } fsServerClient = horizon.CreatePrivilegedHorizonClient(); - var fsServer = new FileSystemServer(fsServerClient); + FileSystemServer fsServer = new(fsServerClient); RandomDataGenerator randomGenerator = Random.Shared.NextBytes; @@ -208,7 +208,7 @@ namespace Ryujinx.HLE.FileSystem SdCard.SetSdCardInserted(true); - var fsServerConfig = new FileSystemServerConfig + FileSystemServerConfig fsServerConfig = new() { ExternalKeySet = KeySet.ExternalKeySet, FsCreators = fsServerObjects.FsCreators, @@ -270,7 +270,7 @@ namespace Ryujinx.HLE.FileSystem { foreach (DirectoryEntryEx ticketEntry in fs.EnumerateEntries("/", "*.tik")) { - using var ticketFile = new UniqueRef(); + using UniqueRef ticketFile = new(); Result result = fs.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); @@ -286,7 +286,7 @@ namespace Ryujinx.HLE.FileSystem continue; Ticket ticket = new(new MemoryStream(ticketData)); - var titleKey = ticket.GetTitleKey(KeySet); + byte[] titleKey = ticket.GetTitleKey(KeySet); if (titleKey != null) { @@ -334,7 +334,7 @@ namespace Ryujinx.HLE.FileSystem { Span info = stackalloc SaveDataInfo[8]; - using var iterator = new UniqueRef(); + using UniqueRef iterator = new(); Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId); if (rc.IsFailure()) @@ -398,7 +398,7 @@ namespace Ryujinx.HLE.FileSystem } const string MountName = "SaveDir"; - var mountNameU8 = MountName.ToU8Span(); + U8Span mountNameU8 = MountName.ToU8Span(); BisPartitionId partitionId = info.SpaceId switch { @@ -415,7 +415,7 @@ namespace Ryujinx.HLE.FileSystem try { - var path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); + U8Span path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); rc = hos.Fs.GetEntryType(out _, path); @@ -437,7 +437,7 @@ namespace Ryujinx.HLE.FileSystem { list = null; - var mountName = "system".ToU8Span(); + U8Span mountName = "system".ToU8Span(); DirectoryHandle handle = default; List localList = []; @@ -498,7 +498,7 @@ namespace Ryujinx.HLE.FileSystem // Only save data IDs added to SystemExtraDataFixInfo will be fixed. private static Result FixUnindexedSystemSaves(HorizonClient hos, List existingSaveIds) { - foreach (var fixInfo in _systemExtraDataFixInfo) + foreach (ExtraDataFixInfo fixInfo in _systemExtraDataFixInfo) { if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId)) { @@ -665,7 +665,7 @@ namespace Ryujinx.HLE.FileSystem { if (disposing) { - foreach (var stream in _romFsByPid.Values) + foreach (Stream stream in _romFsByPid.Values) { stream.Close(); } diff --git a/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs b/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs index 2032806b3..b883a8e1e 100644 --- a/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs +++ b/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs @@ -122,7 +122,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error if (romfs.FileExists(filePath)) { - using var binaryFile = new UniqueRef(); + using UniqueRef binaryFile = new(); romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); StreamReader reader = new(binaryFile.Get.AsStream(), Encoding.Unicode); diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs index 741221f8e..8dce3c1d0 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs @@ -81,8 +81,8 @@ namespace Ryujinx.HLE.HOS.Applets _interactiveSession.DataAvailable += OnInteractiveData; - var launchParams = _normalSession.Pop(); - var keyboardConfig = _normalSession.Pop(); + byte[] launchParams = _normalSession.Pop(); + byte[] keyboardConfig = _normalSession.Pop(); _isBackground = keyboardConfig.Length == Unsafe.SizeOf(); @@ -203,7 +203,7 @@ namespace Ryujinx.HLE.HOS.Applets else { // Call the configured GUI handler to get user's input. - var args = new SoftwareKeyboardUIArgs + SoftwareKeyboardUIArgs args = new() { KeyboardMode = _keyboardForegroundConfig.Mode, HeaderText = StripUnicodeControlCodes(_keyboardForegroundConfig.HeaderText), @@ -263,7 +263,7 @@ namespace Ryujinx.HLE.HOS.Applets private void OnInteractiveData(object sender, EventArgs e) { // Obtain the validation status response. - var data = _interactiveSession.Pop(); + byte[] data = _interactiveSession.Pop(); if (_isBackground) { @@ -318,7 +318,7 @@ namespace Ryujinx.HLE.HOS.Applets using MemoryStream stream = new(data); using BinaryReader reader = new(stream); - var request = (InlineKeyboardRequest)reader.ReadUInt32(); + InlineKeyboardRequest request = (InlineKeyboardRequest)reader.ReadUInt32(); long remaining; @@ -398,14 +398,14 @@ namespace Ryujinx.HLE.HOS.Applets remaining = stream.Length - stream.Position; if (remaining == Marshal.SizeOf()) { - var keyboardCalcData = reader.ReadBytes((int)remaining); - var keyboardCalc = ReadStruct(keyboardCalcData); + byte[] keyboardCalcData = reader.ReadBytes((int)remaining); + SoftwareKeyboardCalc keyboardCalc = ReadStruct(keyboardCalcData); newCalc = keyboardCalc.ToExtended(); } else if (remaining == Marshal.SizeOf() || remaining == SoftwareKeyboardCalcEx.AlternativeSize) { - var keyboardCalcData = reader.ReadBytes((int)remaining); + byte[] keyboardCalcData = reader.ReadBytes((int)remaining); newCalc = ReadStruct(keyboardCalcData); } diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs index 239535ad5..f65d6a018 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs @@ -117,8 +117,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard _state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode); _state.TypingEnabled = typingEnabled.GetValueOrDefault(_state.TypingEnabled); - var begin = _state.CursorBegin; - var end = _state.CursorEnd; + int begin = _state.CursorBegin; + int end = _state.CursorEnd; _state.CursorBegin = Math.Min(begin, end); _state.CursorEnd = Math.Max(begin, end); diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs index 646651836..46b4d6b08 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs @@ -74,10 +74,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard _padCancelIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, padCancelIconPath, 0, 0); _keyModeIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, keyModeIconPath, 0, 0); - var panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255); - var panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150); - var borderColor = ToColor(uiTheme.DefaultBorderColor); - var selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor); + SKColor panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255); + SKColor panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150); + SKColor borderColor = ToColor(uiTheme.DefaultBorderColor); + SKColor selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor); _textNormalColor = ToColor(uiTheme.DefaultForegroundColor); _textSelectedColor = ToColor(uiTheme.SelectionForegroundColor); @@ -134,7 +134,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { try { - using var typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal); + using SKTypeface typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal); _messageFont = new SKFont(typeface, 26); _inputTextFont = new SKFont(typeface, _inputTextFontSize); _labelsTextFont = new SKFont(typeface, 24); @@ -151,10 +151,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private static SKColor ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false) { - var a = (byte)(color.A * 255); - var r = (byte)(color.R * 255); - var g = (byte)(color.G * 255); - var b = (byte)(color.B * 255); + byte a = (byte)(color.A * 255); + byte r = (byte)(color.R * 255); + byte g = (byte)(color.G * 255); + byte b = (byte)(color.B * 255); if (flipRgb) { @@ -177,7 +177,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { Debug.Assert(resourceStream != null); - var bitmap = SKBitmap.Decode(resourceStream); + SKBitmap bitmap = SKBitmap.Decode(resourceStream); if (newHeight != 0 && newWidth != 0) { @@ -198,7 +198,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { return; } - var canvas = _surface.Canvas; + SKCanvas canvas = _surface.Canvas; canvas.Clear(SKColors.Transparent); canvas.DrawRect(_panelRectangle, _panelBrush); @@ -219,18 +219,18 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard return; } - using var paint = new SKPaint(_messageFont) + using SKPaint paint = new SKPaint(_messageFont) { Color = _textNormalColor, IsAntialias = true }; - var canvas = _surface.Canvas; - var messageRectangle = MeasureString(MessageText, paint); + SKCanvas canvas = _surface.Canvas; + SKRect messageRectangle = MeasureString(MessageText, paint); float messagePositionX = (_panelRectangle.Width - messageRectangle.Width) / 2 - messageRectangle.Left; float messagePositionY = _messagePositionY - messageRectangle.Top; - var messagePosition = new SKPoint(messagePositionX, messagePositionY); - var messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height); + SKPoint messagePosition = new(messagePositionX, messagePositionY); + SKRect messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height); canvas.DrawRect(messageBoundRectangle, _panelBrush); @@ -336,12 +336,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private void DrawTextBox(SKCanvas canvas, SoftwareKeyboardUIState state) { - using var textPaint = new SKPaint(_labelsTextFont) + using SKPaint textPaint = new SKPaint(_labelsTextFont) { IsAntialias = true, Color = _textNormalColor }; - var inputTextRectangle = MeasureString(state.InputText, textPaint); + SKRect inputTextRectangle = MeasureString(state.InputText, textPaint); float boxWidth = (int)(Math.Max(300, inputTextRectangle.Width + inputTextRectangle.Left + 8)); float boxHeight = 32; @@ -360,7 +360,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard float inputTextX = (_panelRectangle.Width - inputTextRectangle.Width) / 2 - inputTextRectangle.Left; float inputTextY = boxY + 5; - var inputTextPosition = new SKPoint(inputTextX, inputTextY); + SKPoint inputTextPosition = new(inputTextX, inputTextY); canvas.DrawText(state.InputText, inputTextPosition.X, inputTextPosition.Y + (_labelsTextFont.Metrics.XHeight + _labelsTextFont.Metrics.Descent), textPaint); // Draw the cursor on top of the text and redraw the text with a different color if necessary. @@ -387,8 +387,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard ReadOnlySpan textUntilBegin = state.InputText.AsSpan(0, state.CursorBegin); ReadOnlySpan textUntilEnd = state.InputText.AsSpan(0, state.CursorEnd); - var selectionBeginRectangle = MeasureString(textUntilBegin, textPaint); - var selectionEndRectangle = MeasureString(textUntilEnd, textPaint); + SKRect selectionBeginRectangle = MeasureString(textUntilBegin, textPaint); + SKRect selectionEndRectangle = MeasureString(textUntilEnd, textPaint); cursorVisible = true; cursorPositionXLeft = inputTextX + selectionBeginRectangle.Width + selectionBeginRectangle.Left; @@ -406,7 +406,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard int cursorBegin = Math.Min(state.InputText.Length, state.CursorBegin); ReadOnlySpan textUntilCursor = state.InputText.AsSpan(0, cursorBegin); - var cursorTextRectangle = MeasureString(textUntilCursor, textPaint); + SKRect cursorTextRectangle = MeasureString(textUntilCursor, textPaint); cursorVisible = true; cursorPositionXLeft = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.Left; @@ -452,16 +452,16 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard } else { - var cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight); + SKRect cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight); canvas.DrawRect(cursorRectangle, cursorPen); canvas.DrawRect(cursorRectangle, cursorBrush); - using var textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888)); - var textOverCanvas = textOverCursor.Canvas; - var textRelativePosition = new SKPoint(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top); + using SKSurface textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888)); + SKCanvas textOverCanvas = textOverCursor.Canvas; + SKPoint textRelativePosition = new(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top); - using var cursorPaint = new SKPaint(_inputTextFont) + using SKPaint cursorPaint = new SKPaint(_inputTextFont) { Color = cursorTextColor, IsAntialias = true @@ -469,7 +469,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard textOverCanvas.DrawText(state.InputText, textRelativePosition.X, textRelativePosition.Y + _inputTextFont.Metrics.XHeight + _inputTextFont.Metrics.Descent, cursorPaint); - var cursorPosition = new SKPoint((int)cursorRectangle.Left, (int)cursorRectangle.Top); + SKPoint cursorPosition = new((int)cursorRectangle.Left, (int)cursorRectangle.Top); textOverCursor.Flush(); canvas.DrawSurface(textOverCursor, cursorPosition); } @@ -492,13 +492,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard float iconWidth = icon.Width; float iconHeight = icon.Height; - using var paint = new SKPaint(_labelsTextFont) + using SKPaint paint = new SKPaint(_labelsTextFont) { Color = _textNormalColor, IsAntialias = true }; - var labelRectangle = MeasureString(label, paint); + SKRect labelRectangle = MeasureString(label, paint); float labelPositionX = iconWidth + 8 - labelRectangle.Left; float labelPositionY = 3; @@ -514,13 +514,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard iconX += originX; iconY += originY; - var iconPosition = new SKPoint((int)iconX, (int)iconY); - var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); + SKPoint iconPosition = new((int)iconX, (int)iconY); + SKPoint labelPosition = new(labelPositionX + originX, labelPositionY + originY); - var selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth, + SKRect selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth, fullWidth + 4 * _padPressedPenWidth, fullHeight + 4 * _padPressedPenWidth); - var boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight); + SKRect boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight); boundRectangle.Inflate(4 * _padPressedPenWidth, 4 * _padPressedPenWidth); canvas.DrawRect(boundRectangle, _panelBrush); @@ -545,12 +545,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private void DrawControllerToggle(SKCanvas canvas, SKPoint point) { - using var paint = new SKPaint(_labelsTextFont) + using SKPaint paint = new SKPaint(_labelsTextFont) { IsAntialias = true, Color = _textNormalColor }; - var labelRectangle = MeasureString(ControllerToggleText, paint); + SKRect labelRectangle = MeasureString(ControllerToggleText, paint); // Use relative positions so we can center the entire drawing later. @@ -574,8 +574,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard keyX += originX; keyY += originY; - var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); - var overlayPosition = new SKPoint((int)keyX, (int)keyY); + SKPoint labelPosition = new(labelPositionX + originX, labelPositionY + originY); + SKPoint overlayPosition = new((int)keyX, (int)keyY); canvas.DrawBitmap(_keyModeIcon, overlayPosition); canvas.DrawText(ControllerToggleText, labelPosition.X, labelPosition.Y + _labelsTextFont.Metrics.XHeight, paint); @@ -593,7 +593,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard // Convert the pixel format used in the image to the one used in the Switch surface. _surface.Flush(); - var buffer = new byte[_imageInfo.BytesSize]; + byte[] buffer = new byte[_imageInfo.BytesSize]; fixed (byte* bufferPtr = buffer) { if (!_surface.ReadPixels(_imageInfo, (nint)bufferPtr, _imageInfo.RowBytes, 0, 0)) diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs index a8b137df2..7a6ce8f32 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs @@ -79,11 +79,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action, int totalMilliseconds, int sleepMilliseconds) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new(false); Reset(new Thread(() => { - var substepData = new SleepSubstepData(sleepMilliseconds); + SleepSubstepData substepData = new(sleepMilliseconds); int totalCount = totalMilliseconds / sleepMilliseconds; int totalRemainder = totalMilliseconds - totalCount * sleepMilliseconds; @@ -126,11 +126,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action, int sleepMilliseconds) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new(false); Reset(new Thread(() => { - var substepData = new SleepSubstepData(sleepMilliseconds); + SleepSubstepData substepData = new(sleepMilliseconds); while (!Volatile.Read(ref cancelled.Value)) { @@ -147,7 +147,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new(false); Reset(new Thread(() => { diff --git a/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs b/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs index 6c8d3cb9e..ecb3b4dd8 100644 --- a/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs +++ b/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs @@ -67,21 +67,21 @@ namespace Ryujinx.HLE.HOS { if (OperatingSystem.IsMacOS()) { - var cpuEngine = new HvEngine(_tickSource); - var memoryManager = new HvMemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); + HvEngine cpuEngine = new(_tickSource); + HvMemoryManager memoryManager = new(context.Memory, addressSpaceSize, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit); } else { - if (!AddressSpace.TryCreateWithoutMirror(addressSpaceSize, out var addressSpace)) + if (!AddressSpace.TryCreateWithoutMirror(addressSpaceSize, out MemoryBlock addressSpace)) { throw new Exception("Address space creation failed"); } Logger.Info?.Print(LogClass.Cpu, $"NCE Base AS Address: 0x{addressSpace.Pointer.ToInt64():X} Size: 0x{addressSpace.Size:X}"); - var cpuEngine = new NceEngine(_tickSource); - var memoryManager = new MemoryManagerNative(addressSpace, context.Memory, addressSpaceSize, invalidAccessHandler); + NceEngine cpuEngine = new(_tickSource); + MemoryManagerNative memoryManager = new(addressSpace, context.Memory, addressSpaceSize, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManager, addressSpace.Size, for64Bit, memoryManager.ReservedSize); } } @@ -120,7 +120,7 @@ namespace Ryujinx.HLE.HOS { case MemoryManagerMode.SoftwarePageTable: { - var mm = new MemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); + MemoryManager mm = new(context.Memory, addressSpaceSize, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, mm, addressSpaceSize, for64Bit); } break; @@ -129,7 +129,7 @@ namespace Ryujinx.HLE.HOS case MemoryManagerMode.HostMappedUnsafe: if (addressSpace == null && asNoMirror == null) { - var memoryManagerHostTracked = new MemoryManagerHostTracked(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); + MemoryManagerHostTracked memoryManagerHostTracked = new(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManagerHostTracked, addressSpaceSize, for64Bit); } else @@ -138,12 +138,12 @@ namespace Ryujinx.HLE.HOS if (addressSpace != null) { - var mm = new MemoryManagerHostMapped(addressSpace, unsafeMode, invalidAccessHandler); + MemoryManagerHostMapped mm = new(addressSpace, unsafeMode, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, mm, addressSpace.AddressSpaceSize, for64Bit); } else { - var mm = new MemoryManagerHostNoMirror(asNoMirror, context.Memory, unsafeMode, invalidAccessHandler); + MemoryManagerHostNoMirror mm = new(asNoMirror, context.Memory, unsafeMode, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, mm, asNoMirror.Size, for64Bit); } } diff --git a/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs b/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs index 649e36790..b9b8abb5d 100644 --- a/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs +++ b/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs @@ -32,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private bool ConsumeIf(string toConsume) { - var mangledPart = Mangled.AsSpan(_position); + ReadOnlySpan mangledPart = Mangled.AsSpan(_position); if (mangledPart.StartsWith(toConsume.AsSpan())) { diff --git a/src/Ryujinx.HLE/HOS/Horizon.cs b/src/Ryujinx.HLE/HOS/Horizon.cs index 3006187d1..4c3a5f0e5 100644 --- a/src/Ryujinx.HLE/HOS/Horizon.cs +++ b/src/Ryujinx.HLE/HOS/Horizon.cs @@ -154,11 +154,11 @@ namespace Ryujinx.HLE.HOS timePageList.AddRange(timePa, TimeSize / KPageTableBase.PageSize); appletCaptureBufferPageList.AddRange(appletCaptureBufferPa, AppletCaptureBufferSize / KPageTableBase.PageSize); - var hidStorage = new SharedMemoryStorage(KernelContext, hidPageList); - var fontStorage = new SharedMemoryStorage(KernelContext, fontPageList); - var iirsStorage = new SharedMemoryStorage(KernelContext, iirsPageList); - var timeStorage = new SharedMemoryStorage(KernelContext, timePageList); - var appletCaptureBufferStorage = new SharedMemoryStorage(KernelContext, appletCaptureBufferPageList); + SharedMemoryStorage hidStorage = new(KernelContext, hidPageList); + SharedMemoryStorage fontStorage = new(KernelContext, fontPageList); + SharedMemoryStorage iirsStorage = new(KernelContext, iirsPageList); + SharedMemoryStorage timeStorage = new(KernelContext, timePageList); + SharedMemoryStorage appletCaptureBufferStorage = new(KernelContext, appletCaptureBufferPageList); HidStorage = hidStorage; @@ -265,7 +265,7 @@ namespace Ryujinx.HLE.HOS HorizonFsClient fsClient = new(this); ServiceTable = new ServiceTable(); - var services = ServiceTable.GetServices(new HorizonOptions + IEnumerable services = ServiceTable.GetServices(new HorizonOptions (Device.Configuration.IgnoreMissingServices, LibHacHorizonManager.BcatClient, fsClient, @@ -273,7 +273,7 @@ namespace Ryujinx.HLE.HOS Device.AudioDeviceDriver, TickSource)); - foreach (var service in services) + foreach (ServiceEntry service in services) { const ProcessCreationFlags Flags = ProcessCreationFlags.EnableAslr | @@ -305,7 +305,7 @@ namespace Ryujinx.HLE.HOS public bool LoadKip(string kipPath) { - using var kipFile = new SharedRef(new LocalStorage(kipPath, FileAccess.Read)); + using SharedRef kipFile = new(new LocalStorage(kipPath, FileAccess.Read)); return ProcessLoaderHelper.LoadKip(KernelContext, new KipExecutable(in kipFile)); } diff --git a/src/Ryujinx.HLE/HOS/HorizonFsClient.cs b/src/Ryujinx.HLE/HOS/HorizonFsClient.cs index 3dbafa88b..56bc3bec3 100644 --- a/src/Ryujinx.HLE/HOS/HorizonFsClient.cs +++ b/src/Ryujinx.HLE/HOS/HorizonFsClient.cs @@ -55,8 +55,8 @@ namespace Ryujinx.HLE.HOS Nca nca = new(_system.KeySet, ncaStorage); - using var ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel); - using var ncaFsRef = new UniqueRef(ncaFileSystem); + using IFileSystem ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel); + using UniqueRef ncaFsRef = new(ncaFileSystem); Result result = _fsClient.Register(mountName.ToU8Span(), ref ncaFsRef.Ref).ToHorizonResult(); if (result.IsFailure) @@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS public Result OpenFile(out FileHandle handle, string path, OpenMode openMode) { - var result = _fsClient.OpenFile(out var libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode); + LibHac.Result result = _fsClient.OpenFile(out LibHac.Fs.FileHandle libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode); handle = new(libhacHandle); return result.ToHorizonResult(); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs index e56304d9d..a27bb0074 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs @@ -16,7 +16,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { for (int i = 0; i < MemoryRegions.Length; i++) { - var region = MemoryRegions[i]; + KMemoryRegionManager region = MemoryRegions[i]; if (address >= region.Address && address < region.EndAddr) { @@ -41,7 +41,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { while (pagesCount != 0) { - var region = GetMemoryRegion(address); + KMemoryRegionManager region = GetMemoryRegion(address); ulong countToProcess = Math.Min(pagesCount, region.GetPageOffsetFromEnd(address)); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs index 2eff616c4..270c4ff32 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs @@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory if (result == Result.Success) { - foreach (var node in pageList) + foreach (KPageNode node in pageList) { IncrementPagesReferenceCount(node.Address, node.PagesCount); } diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs index 947983d61..a044ba8b3 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs @@ -162,7 +162,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public bool ClearRange(ulong offset, int count) { int depth = HighestDepthIndex; - var bits = _bitStorages[depth]; + ArraySegment bits = _bitStorages[depth]; int bitInd = (int)(offset / UInt64BitSize); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs index 5bcf703fc..58d79c31f 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs @@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory _blocksCount = blockShifts.Length; _blocks = new Block[_memoryBlockPageShifts.Length]; - var currBitmapStorage = new ArraySegment(new ulong[CalculateManagementOverheadSize(size, blockShifts)]); + ArraySegment currBitmapStorage = new(new ulong[CalculateManagementOverheadSize(size, blockShifts)]); for (int i = 0; i < blockShifts.Length; i++) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs index c494c1a82..8255a38bf 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs @@ -70,7 +70,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public void IncrementPagesReferenceCount(KMemoryManager manager) { - foreach (var node in this) + foreach (KPageNode node in this) { manager.IncrementPagesReferenceCount(node.Address, node.PagesCount); } @@ -78,7 +78,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public void DecrementPagesReferenceCount(KMemoryManager manager) { - foreach (var node in this) + foreach (KPageNode node in this) { manager.DecrementPagesReferenceCount(node.Address, node.PagesCount); } diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs index 4ffa447dd..8985a4244 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs @@ -28,8 +28,8 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory /// protected override void GetPhysicalRegions(ulong va, ulong size, KPageList pageList) { - var ranges = _cpuMemory.GetPhysicalRegions(va, size); - foreach (var range in ranges) + IEnumerable ranges = _cpuMemory.GetPhysicalRegions(va, size); + foreach (MemoryRange range in ranges) { pageList.AddRange(range.Address + DramMemoryMap.DramBase, range.Size / PageSize); } @@ -143,11 +143,11 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory bool shouldFillPages, byte fillValue) { - using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); + using KScopedPageList scopedPageList = new(Context.MemoryManager, pageList); ulong currentVa = address; - foreach (var pageNode in pageList) + foreach (KPageNode pageNode in pageList) { ulong addr = pageNode.Address - DramMemoryMap.DramBase; ulong size = pageNode.PagesCount * PageSize; @@ -188,16 +188,16 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory } } - using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); + using KScopedPageList scopedPageList = new(Context.MemoryManager, pageList); - foreach (var pageNode in pageList) + foreach (KPageNode pageNode in pageList) { Context.CommitMemory(pageNode.Address - DramMemoryMap.DramBase, pageNode.PagesCount * PageSize); } ulong offset = 0; - foreach (var region in regions) + foreach (HostMemoryRange region in regions) { _cpuMemory.MapForeign(va + offset, region.Address, region.Size); @@ -214,9 +214,9 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { KPageList pagesToClose = new(); - var regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize); + IEnumerable regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize); - foreach (var region in regions) + foreach (MemoryRange region in regions) { ulong pa = region.Address + DramMemoryMap.DramBase; if (DramMemoryMap.IsHeapPhysicalAddress(pa)) diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs index 080aa3c88..83f667c04 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs @@ -631,7 +631,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory return result; } - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); return MapPages(address, pageList, permission, MemoryMapFlags.Private); } @@ -783,7 +783,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Result result = region.AllocatePages(out KPageList pageList, pagesCount); - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); void CleanUpForError() { @@ -1355,7 +1355,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Result result = region.AllocatePages(out KPageList pageList, remainingPages); - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); void CleanUpForError() { @@ -1887,7 +1887,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory ulong dstLastPagePa = 0; ulong currentVa = va; - using var _ = new OnScopeExit(() => + using OnScopeExit _ = new(() => { if (dstFirstPagePa != 0) { @@ -1948,7 +1948,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Context.Memory.Fill(GetDramAddressFromPa(dstFirstPagePa), unusedSizeBefore, (byte)_ipcFillValue); ulong copySize = addressRounded <= endAddr ? addressRounded - address : size; - var data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize); + ReadOnlySequence data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstFirstPagePa + unusedSizeBefore), data); @@ -2014,7 +2014,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory if (send) { ulong copySize = endAddr - endAddrTruncated; - var data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize); + ReadOnlySequence data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstLastPagePa), data); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs b/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs index 461a8db8c..112e574b8 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs @@ -1,3 +1,4 @@ +using Ryujinx.Cpu; using Ryujinx.HLE.HOS.Diagnostics.Demangler; using Ryujinx.HLE.HOS.Kernel.Memory; using Ryujinx.HLE.HOS.Kernel.Threading; @@ -50,7 +51,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process { EnsureLoaded(); - var context = thread.Context; + IExecutionContext context = thread.Context; StringBuilder trace = new(); @@ -112,13 +113,13 @@ namespace Ryujinx.HLE.HOS.Kernel.Process { EnsureLoaded(); - var context = thread.Context; + IExecutionContext context = thread.Context; StringBuilder sb = new(); string GetReg(int x) { - var v = x == 32 ? context.Pc : context.GetX(x); + ulong v = x == 32 ? context.Pc : context.GetX(x); if (!AnalyzePointer(out PointerInfo info, v, thread)) { return $"0x{v:x16}"; @@ -253,7 +254,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process { moduleName = string.Empty; - var rodataStart = image.BaseAddress + image.Size; + ulong rodataStart = image.BaseAddress + image.Size; KMemoryInfo roInfo = _owner.MemoryManager.QueryMemory(rodataStart); if (roInfo.Permission != KMemoryPermission.Read) @@ -261,7 +262,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process return false; } - var rwdataStart = roInfo.Address + roInfo.Size; + ulong rwdataStart = roInfo.Address + roInfo.Size; KMemoryInfo.Pool.Release(roInfo); @@ -293,7 +294,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process } pathLength = Math.Min(pathLength, rodataBuf.Length - 8); - var pathBuf = rodataBuf.Slice(8, pathLength); + Span pathBuf = rodataBuf.Slice(8, pathLength); int lastSlash = pathBuf.LastIndexOfAny(new byte[] { (byte)'\\', (byte)'/' }); moduleName = Encoding.ASCII.GetString(pathBuf.Slice(lastSlash + 1).TrimEnd((byte)0)); @@ -311,7 +312,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process info = default; ulong sp = thread.Context.GetX(31); - var memoryInfo = _owner.MemoryManager.QueryMemory(address); + KMemoryInfo memoryInfo = _owner.MemoryManager.QueryMemory(address); MemoryState memoryState = memoryInfo.State; if (!memoryState.HasFlag(MemoryState.Stack)) // Is this pointer within the stack? @@ -461,12 +462,12 @@ namespace Ryujinx.HLE.HOS.Kernel.Process lock (_images) { - var image = new Image(textOffset, textSize, symbols.OrderBy(x => x.Value).ToArray()); + Image image = new(textOffset, textSize, symbols.OrderBy(x => x.Value).ToArray()); string moduleName; if (!GetModuleName(out moduleName, image)) { - var newIndex = _images.Count; + int newIndex = _images.Count; moduleName = $"(unknown{newIndex})"; } image.Name = moduleName; diff --git a/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs b/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs index a7af9dae6..99b58951c 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs @@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KProcess process = new(_context); - using var _ = new OnScopeExit(process.DecrementReferenceCount); + using OnScopeExit _ = new(process.DecrementReferenceCount); KResourceLimit resourceLimit; @@ -1418,7 +1418,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KCodeMemory codeMemory = new(_context); - using var _ = new OnScopeExit(codeMemory.DecrementReferenceCount); + using OnScopeExit _ = new(codeMemory.DecrementReferenceCount); KProcess currentProcess = KernelStatic.GetCurrentProcess(); @@ -2836,7 +2836,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KThread currentThread = KernelStatic.GetCurrentThread(); - var syncObjs = new Span(currentThread.WaitSyncObjects)[..handles.Length]; + Span syncObjs = new Span(currentThread.WaitSyncObjects)[..handles.Length]; if (handles.Length != 0) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs b/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs index 7e3d29851..eb06b5823 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs @@ -127,7 +127,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading public KThread ScheduledThreadsElementAtOrDefault(int core, int index) { int currentIndex = 0; - foreach (var scheduledThread in ScheduledThreads(core)) + foreach (KThread scheduledThread in ScheduledThreads(core)) { if (currentIndex == index) { @@ -144,7 +144,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading public KThread ScheduledThreadsWithDynamicPriorityFirstOrDefault(int core, int dynamicPriority) { - foreach (var scheduledThread in ScheduledThreads(core)) + foreach (KThread scheduledThread in ScheduledThreads(core)) { if (scheduledThread.DynamicPriority == dynamicPriority) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs b/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs index e044b9a21..898bbe5f6 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs @@ -1245,7 +1245,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading { if (_schedulerWaitEvent == null) { - var schedulerWaitEvent = new ManualResetEventSlim(false); + ManualResetEventSlim schedulerWaitEvent = new(false); if (Interlocked.Exchange(ref _schedulerWaitEvent, schedulerWaitEvent) == null) { diff --git a/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs b/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs index 76bfe794c..41911183f 100644 --- a/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs +++ b/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs @@ -54,7 +54,7 @@ namespace Ryujinx.HLE.HOS public void InitializeFsServer(VirtualFileSystem virtualFileSystem) { - virtualFileSystem.InitializeFsServer(Server, out var fsClient); + virtualFileSystem.InitializeFsServer(Server, out HorizonClient fsClient); FsClient = fsClient; } diff --git a/src/Ryujinx.HLE/HOS/ModLoader.cs b/src/Ryujinx.HLE/HOS/ModLoader.cs index 860b97f70..b6cfb6578 100644 --- a/src/Ryujinx.HLE/HOS/ModLoader.cs +++ b/src/Ryujinx.HLE/HOS/ModLoader.cs @@ -3,6 +3,7 @@ using LibHac.Fs; using LibHac.Fs.Fsa; using LibHac.FsSystem; using LibHac.Loader; +using LibHac.Tools.Fs; using LibHac.Tools.FsSystem; using LibHac.Tools.FsSystem.RomFs; using LibHac.Util; @@ -150,7 +151,7 @@ namespace Ryujinx.HLE.HOS private static string EnsureBaseDirStructure(string modsBasePath) { - var modsDir = new DirectoryInfo(modsBasePath); + DirectoryInfo modsDir = new(modsBasePath); modsDir.CreateSubdirectory(AmsContentsDir); modsDir.CreateSubdirectory(AmsNsoPatchDir); @@ -168,23 +169,23 @@ namespace Ryujinx.HLE.HOS { System.Text.StringBuilder types = new(); - foreach (var modDir in dir.EnumerateDirectories()) + foreach (DirectoryInfo modDir in dir.EnumerateDirectories()) { types.Clear(); Mod mod = new("", null, true); if (StrEquals(RomfsDir, modDir.Name) && modDir.Parent != null) { - var modData = modMetadata.Mods.FirstOrDefault(x => modDir.Parent.FullName.Equals(x.Path)); - var enabled = modData?.Enabled ?? true; + Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.Parent.FullName.Equals(x.Path)); + bool enabled = modData?.Enabled ?? true; mods.RomfsDirs.Add(mod = new Mod(dir.Name, modDir, enabled)); types.Append('R'); } else if (StrEquals(ExefsDir, modDir.Name) && modDir.Parent != null) { - var modData = modMetadata.Mods.FirstOrDefault(x => modDir.Parent.FullName.Equals(x.Path)); - var enabled = modData?.Enabled ?? true; + Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.Parent.FullName.Equals(x.Path)); + bool enabled = modData?.Enabled ?? true; mods.ExefsDirs.Add(mod = new Mod(dir.Name, modDir, enabled)); types.Append('E'); @@ -207,8 +208,8 @@ namespace Ryujinx.HLE.HOS public static string GetApplicationDir(string modsBasePath, string applicationId) { - var contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir)); - var applicationModsPath = FindApplicationDir(contentsDir, applicationId); + DirectoryInfo contentsDir = new(Path.Combine(modsBasePath, AmsContentsDir)); + DirectoryInfo applicationModsPath = FindApplicationDir(contentsDir, applicationId); if (applicationModsPath == null) { @@ -250,7 +251,7 @@ namespace Ryujinx.HLE.HOS return; } - foreach (var modDir in patchDir.EnumerateDirectories()) + foreach (DirectoryInfo modDir in patchDir.EnumerateDirectories()) { patches.Add(new Mod(modDir.Name, modDir, true)); Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'"); @@ -279,11 +280,11 @@ namespace Ryujinx.HLE.HOS } } - var fsFile = new FileInfo(Path.Combine(applicationDir.FullName, RomfsContainer)); + FileInfo fsFile = new(Path.Combine(applicationDir.FullName, RomfsContainer)); if (fsFile.Exists) { - var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); - var enabled = modData == null || modData.Enabled; + Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); + bool enabled = modData == null || modData.Enabled; mods.RomfsContainers.Add(new Mod($"<{applicationDir.Name} RomFs>", fsFile, enabled)); } @@ -291,8 +292,8 @@ namespace Ryujinx.HLE.HOS fsFile = new FileInfo(Path.Combine(applicationDir.FullName, ExefsContainer)); if (fsFile.Exists) { - var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); - var enabled = modData == null || modData.Enabled; + Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); + bool enabled = modData == null || modData.Enabled; mods.ExefsContainers.Add(new Mod($"<{applicationDir.Name} ExeFs>", fsFile, enabled)); } @@ -309,7 +310,7 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for {((applicationId & 0x1000) != 0 ? "DLC" : "Application")} {applicationId:X16} in \"{contentsDir.FullName}\""); - var applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}"); + DirectoryInfo applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}"); if (applicationDir != null) { @@ -449,9 +450,9 @@ namespace Ryujinx.HLE.HOS return false; } - foreach (var path in searchDirPaths) + foreach (string path in searchDirPaths) { - var searchDir = new DirectoryInfo(path); + DirectoryInfo searchDir = new(path); if (!searchDir.Exists) { Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist"); @@ -460,7 +461,7 @@ namespace Ryujinx.HLE.HOS if (!TryQuery(searchDir, patches, modCaches)) { - foreach (var subdir in searchDir.EnumerateDirectories()) + foreach (DirectoryInfo subdir in searchDir.EnumerateDirectories()) { TryQuery(subdir, patches, modCaches); } @@ -489,14 +490,14 @@ namespace Ryujinx.HLE.HOS return baseStorage; } - var fileSet = new HashSet(); - var builder = new RomFsBuilder(); + HashSet fileSet = new(); + RomFsBuilder builder = new(); int count = 0; Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Application {applicationId:X16}"); // Prioritize loose files first - foreach (var mod in mods.RomfsDirs) + foreach (Mod mod in mods.RomfsDirs) { if (!mod.Enabled) { @@ -511,7 +512,7 @@ namespace Ryujinx.HLE.HOS } // Then files inside images - foreach (var mod in mods.RomfsContainers) + foreach (Mod mod in mods.RomfsContainers) { if (!mod.Enabled) { @@ -536,12 +537,12 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage..."); // And finally, the base romfs - var baseRom = new RomFsFileSystem(baseStorage); - foreach (var entry in baseRom.EnumerateEntries() + RomFsFileSystem baseRom = new(baseStorage); + foreach (DirectoryEntryEx entry in baseRom.EnumerateEntries() .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath)) .OrderBy(f => f.FullPath, StringComparer.Ordinal)) { - using var file = new UniqueRef(); + using UniqueRef file = new(); baseRom.OpenFile(ref file.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); builder.AddFile(entry.FullPath, file.Release()); @@ -556,12 +557,12 @@ namespace Ryujinx.HLE.HOS private static void AddFiles(IFileSystem fs, string modName, string rootPath, ISet fileSet, RomFsBuilder builder) { - foreach (var entry in fs.EnumerateEntries() + foreach (DirectoryEntryEx entry in fs.EnumerateEntries() .AsParallel() .Where(f => f.Type == DirectoryEntryType.File) .OrderBy(f => f.FullPath, StringComparer.Ordinal)) { - var file = new LazyFile(entry.FullPath, rootPath, fs); + LazyFile file = new(entry.FullPath, rootPath, fs); if (fileSet.Add(entry.FullPath)) { @@ -588,7 +589,7 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, "Using replacement ExeFS partition"); - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new(); pfs.Initialize(mods.ExefsContainers[0].Path.OpenRead().AsStorage()).ThrowIfFailure(); exefs = pfs; @@ -626,9 +627,9 @@ namespace Ryujinx.HLE.HOS throw new ArgumentOutOfRangeException(nameof(nsos), nsos.Length, "NSO Count is incorrect"); } - var exeMods = mods.ExefsDirs; + List> exeMods = mods.ExefsDirs; - foreach (var mod in exeMods) + foreach (Mod mod in exeMods) { if (!mod.Enabled) { @@ -637,7 +638,7 @@ namespace Ryujinx.HLE.HOS for (int i = 0; i < ProcessConst.ExeFsPrefixes.Length; ++i) { - var nsoName = ProcessConst.ExeFsPrefixes[i]; + string nsoName = ProcessConst.ExeFsPrefixes[i]; FileInfo nsoFile = new(Path.Combine(mod.Path.FullName, nsoName)); if (nsoFile.Exists) @@ -705,7 +706,7 @@ namespace Ryujinx.HLE.HOS internal void ApplyNroPatches(NroExecutable nro) { - var nroPatches = _patches.NroPatches; + List> nroPatches = _patches.NroPatches; if (nroPatches.Count == 0) { @@ -747,11 +748,11 @@ namespace Ryujinx.HLE.HOS return; } - var cheats = mods.Cheats; - var processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v }) + List cheats = mods.Cheats; + Dictionary processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v }) .ToDictionary(x => x.k[..Math.Min(Cheat.CheatIdSize, x.k.Length)], x => x.v); - foreach (var cheat in cheats) + foreach (Cheat cheat in cheats) { string cheatId = Path.GetFileNameWithoutExtension(cheat.Path.Name).ToUpper(); @@ -772,7 +773,7 @@ namespace Ryujinx.HLE.HOS internal static void EnableCheats(ulong applicationId, TamperMachine tamperMachine) { - var contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}"); + DirectoryInfo contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}"); string enabledCheatsPath = Path.Combine(contentDirectory.FullName, CheatDir, "enabled.txt"); if (File.Exists(enabledCheatsPath)) @@ -792,11 +793,11 @@ namespace Ryujinx.HLE.HOS patches[i] = new MemPatch(); } - var buildIds = new List(programs.Length); + List buildIds = new(programs.Length); foreach (IExecutable p in programs) { - var buildId = p switch + string buildId = p switch { NsoExecutable nso => Convert.ToHexString(nso.BuildId).TrimEnd('0'), NroExecutable nro => Convert.ToHexString(nro.Header.BuildId).TrimEnd('0'), @@ -808,15 +809,15 @@ namespace Ryujinx.HLE.HOS int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small // Collect patches - foreach (var mod in mods) + foreach (Mod mod in mods) { if (!mod.Enabled) { continue; } - var patchDir = mod.Path; - foreach (var patchFile in patchDir.EnumerateFiles()) + DirectoryInfo patchDir = mod.Path; + foreach (FileInfo patchFile in patchDir.EnumerateFiles()) { if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32 { @@ -831,18 +832,18 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}"); - using var fs = patchFile.OpenRead(); - using var reader = new BinaryReader(fs); + using FileStream fs = patchFile.OpenRead(); + using BinaryReader reader = new(fs); - var patcher = new IpsPatcher(reader); + IpsPatcher patcher = new(reader); patcher.AddPatches(patches[index]); } else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch { - using var fs = patchFile.OpenRead(); - using var reader = new StreamReader(fs); + using FileStream fs = patchFile.OpenRead(); + using StreamReader reader = new(fs); - var patcher = new IPSwitchPatcher(reader); + IPSwitchPatcher patcher = new(reader); int index = GetIndex(patcher.BuildId); if (index == -1) diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs index a6807a85a..0a8e84577 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs @@ -191,10 +191,10 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc private void DeleteSaveData(UserId userId) { - var saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default, + SaveDataFilter saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default, new LibHac.Fs.UserId((ulong)userId.High, (ulong)userId.Low), saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new(); _horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs index 388ad6036..f867d249a 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs @@ -5,6 +5,7 @@ using Ryujinx.Common.Utilities; using Ryujinx.HLE.HOS.Services.Account.Acc.Types; using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; @@ -28,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc { ProfilesJson profilesJson = JsonHelper.DeserializeFromFile(_profilesJsonPath, _serializerContext.ProfilesJson); - foreach (var profile in profilesJson.Profiles) + foreach (UserProfileJson profile in profilesJson.Profiles) { UserProfile addedProfile = new(new UserId(profile.UserId), profile.Name, profile.Image, profile.LastModifiedTimestamp); @@ -68,7 +69,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc LastOpened = LastOpened.ToString(), }; - foreach (var profile in profiles) + foreach (KeyValuePair profile in profiles) { profilesJson.Profiles.Add(new UserProfileJson() { diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs index 3d94f6c28..911296ff5 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs @@ -51,7 +51,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc.AccountService byte[] deviceAccountId = new byte[0x10]; RandomNumberGenerator.Fill(deviceAccountId); - var descriptor = new SecurityTokenDescriptor + SecurityTokenDescriptor descriptor = new() { Subject = new ClaimsIdentity([new Claim(JwtRegisteredClaimNames.Sub, Convert.ToHexString(rawUserId).ToLower())]), SigningCredentials = credentials, diff --git a/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs b/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs index 602fc2c4d..ad776fe6e 100644 --- a/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs +++ b/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs @@ -214,7 +214,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletAE.AllSystemAppletProxiesService.Sys _vrModeEnabled = vrModeEnabled; - using var lblApi = new LblApi(); + using LblApi lblApi = new(); if (vrModeEnabled) { diff --git a/src/Ryujinx.HLE/HOS/Services/Am/AppletOE/ApplicationProxyService/ApplicationProxy/IApplicationFunctions.cs b/src/Ryujinx.HLE/HOS/Services/Am/AppletOE/ApplicationProxyService/ApplicationProxy/IApplicationFunctions.cs index 097ca535b..88c0c1d22 100644 --- a/src/Ryujinx.HLE/HOS/Services/Am/AppletOE/ApplicationProxyService/ApplicationProxy/IApplicationFunctions.cs +++ b/src/Ryujinx.HLE/HOS/Services/Am/AppletOE/ApplicationProxyService/ApplicationProxy/IApplicationFunctions.cs @@ -13,6 +13,7 @@ using Ryujinx.HLE.HOS.Services.Am.AppletAE.Storage; using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types; using Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService; using Ryujinx.HLE.HOS.SystemState; +using Ryujinx.HLE.Loaders.Processes; using Ryujinx.Horizon.Common; using System; using System.Numerics; @@ -117,7 +118,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.Applicati public ResultCode EnsureSaveData(ServiceCtx context) { Uid userId = context.RequestData.ReadStruct().ToLibHacUid(); - var process = context.Device.Processes.GetProcess(_pid); + ProcessResult process = context.Device.Processes.GetProcess(_pid); // Mask out the low nibble of the program ID to get the application ID ApplicationId applicationId = new(process.Identity.ApplicationId); @@ -238,7 +239,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.Applicati ushort index = (ushort)context.RequestData.ReadUInt64(); long saveSize = context.RequestData.ReadInt64(); long journalSize = context.RequestData.ReadInt64(); - var process = context.Device.Processes.GetProcess(_pid); + ProcessResult process = context.Device.Processes.GetProcess(_pid); // Mask out the low nibble of the program ID to get the application ID ApplicationId applicationId = new(process.Identity.ApplicationId); diff --git a/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs b/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs index 3fe905646..bbd5777ef 100644 --- a/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs @@ -131,7 +131,7 @@ namespace Ryujinx.HLE.HOS.Services.Caps filePath = GenerateFilePath(folderPath, applicationAlbumEntry, currentDateTime, hash); } - using var bitmap = new SKBitmap(new SKImageInfo(ScreenshotWidth, ScreenshotHeight, SKColorType.Rgba8888)); + using SKBitmap bitmap = new(new SKImageInfo(ScreenshotWidth, ScreenshotHeight, SKColorType.Rgba8888)); IntPtr pixels = bitmap.GetPixels(); @@ -143,7 +143,7 @@ namespace Ryujinx.HLE.HOS.Services.Caps Marshal.Copy(screenshotData, 0, pixels, ScreenshotDataSize); using var data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 80); - using var file = File.OpenWrite(filePath); + using FileStream file = File.OpenWrite(filePath); data.SaveTo(file); return ResultCode.Success; diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs index e05d5a751..9d4e1fd69 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs @@ -26,7 +26,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy try { LocalStorage storage = new(pfsPath, FileAccess.Read, FileMode.Open); - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new(); using SharedRef nsp = new(pfs); pfs.Initialize(storage).ThrowIfFailure(); @@ -58,7 +58,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy } LibHac.Fs.Fsa.IFileSystem fileSystem = nca.OpenFileSystem(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel); - using var sharedFs = new SharedRef(fileSystem); + using SharedRef sharedFs = new(fileSystem); using SharedRef adapter = FileSystemInterfaceAdapter.CreateShared(ref sharedFs.Ref, true); @@ -99,7 +99,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\'); - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); Result result = nsp.OpenFile(ref ncaFile.Ref, filename.ToU8Span(), OpenMode.Read); if (result.IsFailure()) @@ -122,14 +122,14 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik")) { - using var ticketFile = new UniqueRef(); + using UniqueRef ticketFile = new(); Result result = nsp.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); if (result.IsSuccess()) { Ticket ticket = new(ticketFile.Get.AsStream()); - var titleKey = ticket.GetTitleKey(keySet); + byte[] titleKey = ticket.GetTitleKey(keySet); if (titleKey != null) { diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs index 70d3a6bd8..0fe7bcdd6 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs @@ -1,6 +1,7 @@ using LibHac; using LibHac.Common; using LibHac.Sf; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { @@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseDirectory.Get.Read(out long entriesRead, new OutBuffer(region.Memory.Span)); context.ResponseData.Write(entriesRead); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs index dcc34a754..0ea57f5a4 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs @@ -3,6 +3,7 @@ using LibHac.Common; using LibHac.Fs; using LibHac.Sf; using Ryujinx.Common; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { @@ -28,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy long offset = context.RequestData.ReadInt64(); long size = context.RequestData.ReadInt64(); - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseFile.Get.Read(out long bytesRead, offset, new OutBuffer(region.Memory.Span), size, readOption); context.ResponseData.Write(bytesRead); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs index f0393f64f..168dfc37a 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs @@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy uint mode = context.RequestData.ReadUInt32(); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); - using var file = new SharedRef(); + using SharedRef file = new(); Result result = _fileSystem.Get.OpenFile(ref file.Ref, in name, mode); @@ -132,7 +132,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy uint mode = context.RequestData.ReadUInt32(); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); - using var dir = new SharedRef(); + using SharedRef dir = new(); Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, in name, mode); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs index 4299a6c74..30cfc06bb 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs @@ -1,6 +1,7 @@ using LibHac; using LibHac.Common; using LibHac.Sf; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { @@ -31,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy size = bufferLen; } - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseStorage.Get.Read((long)offset, new OutBuffer(region.Memory.Span), (long)size); return (ResultCode)result.Value; diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs b/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs index 7ed6dadc2..b86eb1fa1 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs @@ -1,6 +1,7 @@ using LibHac; using LibHac.Common; using LibHac.Sf; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs { @@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseReader.Get.Read(out long readCount, new OutBuffer(region.Memory.Span)); context.ResponseData.Write(readCount); diff --git a/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs b/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs index a13e77e72..28caf4459 100644 --- a/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs @@ -81,7 +81,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedMomentProcessorConfig = context.RequestData.ReadStruct(); + PackedMomentProcessorConfig packedMomentProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedClusteringProcessorConfig = context.RequestData.ReadStruct(); + PackedClusteringProcessorConfig packedClusteringProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedImageTransferProcessorConfig = context.RequestData.ReadStruct(); + PackedImageTransferProcessorConfig packedImageTransferProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -157,7 +157,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedTeraPluginProcessorConfig = context.RequestData.ReadStruct(); + PackedTeraPluginProcessorConfig packedTeraPluginProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs index 563745238..c29af43da 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs @@ -248,7 +248,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm byte[] ip = address.GetAddressBytes(); - var macAddress = new Array6(); + Array6 macAddress = new(); new byte[] { 0x02, 0x00, ip[0], ip[1], ip[2], ip[3] }.CopyTo(macAddress.AsSpan()); return macAddress; diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs index 536ae476d..374871311 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs @@ -112,7 +112,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy lock (_scanLock) { - var newResults = _scanResultsLast; + Dictionary newResults = _scanResultsLast; newResults.Clear(); _scanResultsLast = _scanResults; @@ -138,7 +138,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy lock (_scanLock) { - var results = new Dictionary(); + Dictionary results = new(); foreach (KeyValuePair last in _scanResultsLast) { diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs index bd0b93438..661d91b98 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs @@ -493,7 +493,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu SendAsync(_protocol.Encode(PacketId.CreateAccessPoint, request, advertiseData)); // Send a network change event with dummy data immediately. Necessary to avoid crashes in some games - var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() + NetworkChangeEventArgs networkChangeEvent = new(new NetworkInfo() { Common = new CommonNetworkInfo() { @@ -613,7 +613,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu SendAsync(_protocol.Encode(PacketId.Connect, request)); - var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() + NetworkChangeEventArgs networkChangeEvent = new(new NetworkInfo() { Common = request.NetworkInfo.Common, Ldn = request.NetworkInfo.Ldn diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs index 4a0b39bcd..e792bb91e 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs @@ -256,7 +256,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy { _proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port); } - var asIPEndpoint = (IPEndPoint)localEP; + IPEndPoint asIPEndpoint = (IPEndPoint)localEP; if (asIPEndpoint.Port == 0) { asIPEndpoint.Port = (ushort)_proxy.GetEphemeralPort(ProtocolType); diff --git a/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs b/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs index e8911e210..5053cd5ca 100644 --- a/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs +++ b/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs @@ -440,18 +440,18 @@ namespace Ryujinx.HLE.HOS.Services.Mii.Types int indexFor4 = 3 * (int)age + 9 * (int)gender + (int)race; - var facelineTypeInfo = RandomMiiFacelineArray[indexFor4]; - var facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race]; - var facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4]; - var facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4]; - var hairTypeInfo = RandomMiiHairTypeArray[indexFor4]; - var hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age]; - var eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4]; - var eyeColorInfo = RandomMiiEyeColorArray[(int)race]; - var eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4]; - var noseTypeInfo = RandomMiiNoseTypeArray[indexFor4]; - var mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4]; - var glassTypeInfo = RandomMiiGlassTypeArray[(int)age]; + RandomMiiData4 facelineTypeInfo = RandomMiiFacelineArray[indexFor4]; + RandomMiiData3 facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race]; + RandomMiiData4 facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4]; + RandomMiiData4 facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4]; + RandomMiiData4 hairTypeInfo = RandomMiiHairTypeArray[indexFor4]; + RandomMiiData3 hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age]; + RandomMiiData4 eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4]; + RandomMiiData2 eyeColorInfo = RandomMiiEyeColorArray[(int)race]; + RandomMiiData4 eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4]; + RandomMiiData4 noseTypeInfo = RandomMiiNoseTypeArray[indexFor4]; + RandomMiiData4 mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4]; + RandomMiiData2 glassTypeInfo = RandomMiiGlassTypeArray[(int)age]; // Faceline coreData.FacelineType = (FacelineType)facelineTypeInfo.Values[utilImpl.GetRandom(facelineTypeInfo.ValuesCount)]; diff --git a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs index cc6d02ea2..245c37742 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs @@ -9,8 +9,8 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption public AmiiboDecryptor(string keyRetailBinPath) { - var combinedKeys = File.ReadAllBytes(keyRetailBinPath); - var keys = AmiiboMasterKey.FromCombinedBin(combinedKeys); + byte[] combinedKeys = File.ReadAllBytes(keyRetailBinPath); + (AmiiboMasterKey DataKey, AmiiboMasterKey TagKey) keys = AmiiboMasterKey.FromCombinedBin(combinedKeys); DataKey = keys.DataKey; TagKey = keys.TagKey; } diff --git a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs index 37d587dac..9873ae1be 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs @@ -85,13 +85,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption if (deriveAes) { // Derive AES Key and IV - var dataForAes = new byte[2 + seedBytes.Length]; + byte[] dataForAes = new byte[2 + seedBytes.Length]; dataForAes[0] = 0x00; dataForAes[1] = 0x00; // Counter (0) Array.Copy(seedBytes, 0, dataForAes, 2, seedBytes.Length); byte[] derivedBytes; - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForAes); } @@ -100,12 +100,12 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption derivedAesIv = derivedBytes.Skip(16).Take(16).ToArray(); // Derive HMAC Key - var dataForHmacKey = new byte[2 + seedBytes.Length]; + byte[] dataForHmacKey = new byte[2 + seedBytes.Length]; dataForHmacKey[0] = 0x00; dataForHmacKey[1] = 0x01; // Counter (1) Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForHmacKey); } @@ -115,13 +115,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption else { // Derive HMAC Key only - var dataForHmacKey = new byte[2 + seedBytes.Length]; + byte[] dataForHmacKey = new byte[2 + seedBytes.Length]; dataForHmacKey[0] = 0x00; dataForHmacKey[1] = 0x01; // Counter (1) Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); byte[] derivedBytes; - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForHmacKey); } @@ -229,7 +229,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, tagHmacData, 8, 44); byte[] tagHmac; - using (var hmac = new HMACSHA256(hmacTagKey)) + using (HMACSHA256 hmac = new(hmacTagKey)) { tagHmac = hmac.ComputeHash(tagHmacData); } @@ -258,7 +258,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, dataHmacData, offset, len5); byte[] dataHmac; - using (var hmac = new HMACSHA256(hmacDataKey)) + using (HMACSHA256 hmac = new(hmacDataKey)) { dataHmac = hmac.ComputeHash(dataHmacData); } @@ -278,7 +278,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, tagHmacData, 8, 44); byte[] calculatedTagHmac; - using (var hmac = new HMACSHA256(hmacTagKey)) + using (HMACSHA256 hmac = new(hmacTagKey)) { calculatedTagHmac = hmac.ComputeHash(tagHmacData); } @@ -312,7 +312,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, dataHmacData, offset, len5); byte[] calculatedDataHmac; - using (var hmac = new HMACSHA256(hmacDataKey)) + using (HMACSHA256 hmac = new(hmacDataKey)) { calculatedDataHmac = hmac.ComputeHash(dataHmacData); } diff --git a/src/Ryujinx.HLE/HOS/Services/Nfc/Nfp/NfpManager/INfp.cs b/src/Ryujinx.HLE/HOS/Services/Nfc/Nfp/NfpManager/INfp.cs index 307dfdadc..522de891f 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nfc/Nfp/NfpManager/INfp.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nfc/Nfp/NfpManager/INfp.cs @@ -146,11 +146,11 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp context.Device.System.NfpDevices[i].State = NfpDeviceState.SearchingForTag; // â–¼ If a tag has already been injected via Bridge, use it immediately. - if (KenjinxAmiiboShim.TryConsume(out var tagBytes)) + if (KenjinxAmiiboShim.TryConsume(out byte[] tagBytes)) { - var dev = context.Device.System.NfpDevices[i]; + NfpDevice dev = context.Device.System.NfpDevices[i]; - if (TryGetFigureIdFrom1Dc(tagBytes, out var fid, out var raw)) + if (TryGetFigureIdFrom1Dc(tagBytes, out string fid, out string raw)) { dev.AmiiboId = fid; Logger.Info?.PrintMsg(LogClass.ServiceNfp, $"Kenjinx: raw@1DC={raw} → FigureID={fid}"); @@ -182,11 +182,11 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp // â–¼ Poll during the search for newly injected tags. for (int d = 0; d < context.Device.System.NfpDevices.Count; d++) { - var dev = context.Device.System.NfpDevices[d]; + NfpDevice dev = context.Device.System.NfpDevices[d]; - if (dev.State == NfpDeviceState.SearchingForTag && KenjinxAmiiboShim.TryConsume(out var tagBytesLoop)) + if (dev.State == NfpDeviceState.SearchingForTag && KenjinxAmiiboShim.TryConsume(out byte[] tagBytesLoop)) { - if (TryGetFigureIdFrom1Dc(tagBytesLoop, out var fid, out var raw)) + if (TryGetFigureIdFrom1Dc(tagBytesLoop, out string fid, out string raw)) { dev.AmiiboId = fid; Logger.Info?.PrintMsg(LogClass.ServiceNfp, $"Kenjinx: raw@1DC={raw} → FigureID={fid}"); @@ -267,7 +267,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp return false; } - var s = data.AsSpan(off, len); + Span s = data.AsSpan(off, len); // Debug string "AA-BB-..." in uppercase letters debugRaw = $"{s[0]:X2}-{s[1]:X2}-{s[2]:X2}-{s[3]:X2}-{s[4]:X2}-{s[5]:X2}-{s[6]:X2}-{s[7]:X2}"; @@ -286,8 +286,8 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp { if (data == null || data.Length == 0) return "0000000000000000"; - using var sha = SHA1.Create(); - var hash = sha.ComputeHash(data); // 20 Bytes + using SHA1 sha = SHA1.Create(); + byte[] hash = sha.ComputeHash(data); // 20 Bytes char[] buf = new char[16]; for (int i = 0, k = 0; i < 8; i++) { diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs b/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs index 7c7ebf22d..b8495f643 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs @@ -18,8 +18,8 @@ namespace Ryujinx.HLE.HOS.Services.Nv MemoryAllocator = new NvMemoryAllocator(); Host1x = new Host1xDevice(gpu.Synchronization); Smmu = gpu.CreateDeviceMemoryManager(pid); - var nvdec = new NvdecDevice(Smmu); - var vic = new VicDevice(Smmu); + NvdecDevice nvdec = new(Smmu); + VicDevice vic = new(Smmu); Host1x.RegisterDevice(ClassId.Nvdec, nvdec); Host1x.RegisterDevice(ClassId.Vic, vic); } diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs index 3b0b47964..3f0b01a69 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs @@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu private NvInternalResult BindChannel(ref BindChannelArguments arguments) { - var channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData(arguments.Fd); + NvHostChannelDeviceFile channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData(arguments.Fd); if (channelDeviceFile == null) { // TODO: Return invalid Fd error. @@ -339,9 +339,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu for (uint i = 0; i < writeEntries; i++) { - ref var region = ref regionsSpan[(int)i]; + ref VaRegion region = ref regionsSpan[(int)i]; - var vmRegion = _vmRegions[i]; + VmRegion vmRegion = _vmRegions[i]; uint pageSize = _pageSizes[i]; region.PageSize = pageSize; diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/Types/AddressSpaceContext.cs b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/Types/AddressSpaceContext.cs index 36530f89e..5d48addc2 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/Types/AddressSpaceContext.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/Types/AddressSpaceContext.cs @@ -125,7 +125,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu.Types public void Close() { - foreach (var map in _maps.Values) + foreach (Range map in _maps.Values) { Gmm.Unmap(map.Start, map.End - map.Start); } diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs index 71d884276..9d49924bc 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs @@ -169,7 +169,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel { NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, commandBuffer.Mem); - var data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4); + ReadOnlySpan data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4); _host1xContext.Host1x.Submit(MemoryMarshal.Cast(data), _contextId); } diff --git a/src/Ryujinx.HLE/HOS/Services/Pctl/ParentalControlServiceFactory/IParentalControlService.cs b/src/Ryujinx.HLE/HOS/Services/Pctl/ParentalControlServiceFactory/IParentalControlService.cs index 4c0fe9d6e..782cdefde 100644 --- a/src/Ryujinx.HLE/HOS/Services/Pctl/ParentalControlServiceFactory/IParentalControlService.cs +++ b/src/Ryujinx.HLE/HOS/Services/Pctl/ParentalControlServiceFactory/IParentalControlService.cs @@ -1,5 +1,6 @@ using Ryujinx.Common.Logging; using Ryujinx.HLE.HOS.Services.Arp; +using Ryujinx.HLE.Loaders.Processes; using System; using static LibHac.Ns.ApplicationControlProperty; @@ -53,7 +54,7 @@ namespace Ryujinx.HLE.HOS.Services.Pctl.ParentalControlServiceFactory if (titleId != 0) { _titleId = titleId; - var process = context.Device.Processes.GetProcess(_pid); + ProcessResult process = context.Device.Processes.GetProcess(_pid); // TODO: Call nn::arp::GetApplicationControlProperty here when implemented, if it return ResultCode.Success we assign fields. _ratingAge = new int[process.ApplicationControlProperties.RatingAge.Length]; diff --git a/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs b/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs index 2687d05b1..3999512ef 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs @@ -57,7 +57,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize); // Return ResultCode.ServiceUnavailable if data is locked by another process. - var filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable(); + IEnumerable> filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable(); if (queryCapability == PlayLogQueryCapability.None) { diff --git a/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs b/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs index 641795890..739faea57 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs @@ -76,7 +76,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pl Nca nca = new(_device.System.KeySet, ncaFileStream); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel); - using var fontFile = new UniqueRef(); + using UniqueRef fontFile = new(); romfs.OpenFile(ref fontFile.Ref, ("/" + fontFilename).ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/HOS/Services/ServerBase.cs b/src/Ryujinx.HLE/HOS/Services/ServerBase.cs index baff40225..34502c51e 100644 --- a/src/Ryujinx.HLE/HOS/Services/ServerBase.cs +++ b/src/Ryujinx.HLE/HOS/Services/ServerBase.cs @@ -1,3 +1,4 @@ +using Microsoft.IO; using Ryujinx.Common; using Ryujinx.Common.Logging; using Ryujinx.Common.Memory; @@ -82,7 +83,7 @@ namespace Ryujinx.HLE.HOS.Services KernelStatic.StartInitialProcess(context, creationInfo, _defaultCapabilities, 44, () => { - var currentThread = KernelStatic.GetCurrentThread(); + KThread currentThread = KernelStatic.GetCurrentThread(); currentThread.HostThread.Name = $"{{{Name}}}"; Main(); @@ -241,7 +242,7 @@ namespace Ryujinx.HLE.HOS.Services } } - var rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1); + Result rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1); _selfThread.HandlePostSyscall(); @@ -313,7 +314,7 @@ namespace Ryujinx.HLE.HOS.Services { _context.Syscall.CloseHandle(serverSessionHandle); - if (RemoveSessionObj(serverSessionHandle, out var session)) + if (RemoveSessionObj(serverSessionHandle, out IpcService session)) { (session as IDisposable)?.Dispose(); } @@ -466,7 +467,7 @@ namespace Ryujinx.HLE.HOS.Services response.RawData = _responseDataStream.ToArray(); - var responseStream = response.GetStreamTipc(); + RecyclableMemoryStream responseStream = response.GetStreamTipc(); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); MemoryStreamManager.Shared.ReleaseStream(responseStream); } @@ -477,7 +478,7 @@ namespace Ryujinx.HLE.HOS.Services if (!isTipcCommunication) { - var responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48)); + RecyclableMemoryStream responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48)); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); MemoryStreamManager.Shared.ReleaseStream(responseStream); } diff --git a/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs b/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs index 846c4dc4f..cfad2884a 100644 --- a/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs @@ -326,7 +326,7 @@ namespace Ryujinx.HLE.HOS.Services.Settings IFileSystem firmwareRomFs = firmwareContent.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel); - using var firmwareFile = new UniqueRef(); + using UniqueRef firmwareFile = new(); Result result = firmwareRomFs.OpenFile(ref firmwareFile.Ref, "/file".ToU8Span(), OpenMode.Read); if (result.IsFailure()) diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs index 0f0bb2950..e32de3fe1 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs @@ -331,9 +331,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd } } - using var readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize); - using var writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize); - using var errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize); + using WritableRegion readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize); + using WritableRegion writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize); + using WritableRegion errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize); _context.BuildMask(readFds, readFdsOut.Memory.Span); _context.BuildMask(writeFds, writeFdsOut.Memory.Span); diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs index dd2f246f1..018bb8f14 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs @@ -304,7 +304,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl public static bool TryConvertSocketOption(BsdSocketOption option, SocketOptionLevel level, out SocketOptionName name) { - var table = level switch + Dictionary table = level switch { SocketOptionLevel.Socket => _soSocketOptionMap, SocketOptionLevel.IP => _ipSocketOptionMap, @@ -323,7 +323,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl public static LinuxError ValidateSocketOption(BsdSocketOption option, SocketOptionLevel level, bool write) { - var table = level switch + Dictionary table = level switch { SocketOptionLevel.Socket => _validSoSocketOptionMap, SocketOptionLevel.IP => _validIpSocketOptionMap, diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs index 77d9a7b1a..660803714 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs @@ -13,9 +13,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy public static void Select(List readEvents, List writeEvents, List errorEvents, int timeout) { - var readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); - var writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); - var errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); if (readDefault.Count != 0 || writeDefault.Count != 0 || errorDefault.Count != 0) { diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs index a1aa3f8be..820a4ab48 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs @@ -82,7 +82,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Proxy public IPHostEntry ResolveAddress(string host) { - foreach (var hostEntry in _mitmHostEntries) + foreach (KeyValuePair hostEntry in _mitmHostEntries) { // Check for AMS hosts file extension: "*" // NOTE: MatchesSimpleExpression also allows "?" as a wildcard diff --git a/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs b/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs index 68e871d1b..90c05a637 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs @@ -129,7 +129,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var trustedCertsFileRef = new UniqueRef(); + using UniqueRef trustedCertsFileRef = new(); Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read); diff --git a/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs b/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs index b5c608d3d..92e73f9f1 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs @@ -145,7 +145,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl.SslService ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using (var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true)) + using (WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true)) { Encoding.ASCII.GetBytes(_hostName, region.Memory.Span); } diff --git a/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs b/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs index 2dd787187..c3f29cef8 100644 --- a/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs @@ -94,7 +94,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone Nca nca = new(_virtualFileSystem.KeySet, ncaFileStream); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var binaryListFile = new UniqueRef(); + using UniqueRef binaryListFile = new(); romfs.OpenFile(ref binaryListFile.Ref, "/binaryList.txt".ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -120,7 +120,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone public IEnumerable<(int Offset, string Location, string Abbr)> ParseTzOffsets() { - var tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath(); + string tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath(); if (string.IsNullOrEmpty(tzBinaryContentPath)) { @@ -128,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone } List<(int Offset, string Location, string Abbr)> outList = []; - var now = DateTimeOffset.Now.ToUnixTimeSeconds(); + long now = DateTimeOffset.Now.ToUnixTimeSeconds(); using (IStorage ncaStorage = new LocalStorage(VirtualFileSystem.SwitchPathToSystemPath(tzBinaryContentPath), FileAccess.Read, FileMode.Open)) using (IFileSystem romfs = new Nca(_virtualFileSystem.KeySet, ncaStorage).OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel)) { @@ -139,7 +139,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone continue; } - using var tzif = new UniqueRef(); + using UniqueRef tzif = new(); if (romfs.OpenFile(ref tzif.Ref, $"/zoneinfo/{locName}".ToU8Span(), OpenMode.Read).IsFailure()) { @@ -176,7 +176,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone continue; } - var abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..]; + Span abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..]; int abbrEnd = abbrStart.IndexOf((byte)0); outList.Add((ttInfo.GmtOffset, locName, Encoding.UTF8.GetString(abbrStart[..abbrEnd]))); @@ -269,7 +269,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone Nca nca = new(_virtualFileSystem.KeySet, ncaFile); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var timeZoneBinaryFile = new UniqueRef(); + using UniqueRef timeZoneBinaryFile = new(); Result result = romfs.OpenFile(ref timeZoneBinaryFile.Ref, $"/zoneinfo/{locationName}".ToU8Span(), OpenMode.Read); diff --git a/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs b/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs index fc7edd62b..5eaed6530 100644 --- a/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs +++ b/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs @@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Tamper.CodeEmitters } // Use the conditional begin instruction stored in the stack. - var upperInstruction = context.CurrentBlock.BaseInstruction; + byte[] upperInstruction = context.CurrentBlock.BaseInstruction; CodeType codeType = InstructionHelper.GetCodeType(upperInstruction); // Pop the current block of operations from the stack so control instructions diff --git a/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs b/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs index 759ba5f90..46e4fd9f7 100644 --- a/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs +++ b/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs @@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Tamper // Instructions are multi-word, with 32bit words. Split the raw instruction // and parse each word into individual nybbles of bits. - var words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + string[] words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); byte[] instruction = new byte[WordSize * words.Length]; diff --git a/src/Ryujinx.HLE/HOS/TamperMachine.cs b/src/Ryujinx.HLE/HOS/TamperMachine.cs index 00cbc937d..157c981fd 100644 --- a/src/Ryujinx.HLE/HOS/TamperMachine.cs +++ b/src/Ryujinx.HLE/HOS/TamperMachine.cs @@ -73,14 +73,14 @@ namespace Ryujinx.HLE.HOS public void EnableCheats(string[] enabledCheats) { - foreach (var program in _programDictionary.Values) + foreach (ITamperProgram program in _programDictionary.Values) { program.IsEnabled = false; } - foreach (var cheat in enabledCheats) + foreach (string cheat in enabledCheats) { - if (_programDictionary.TryGetValue(cheat, out var program)) + if (_programDictionary.TryGetValue(cheat, out ITamperProgram program)) { program.IsEnabled = true; } diff --git a/src/Ryujinx.HLE/Kenjinx/AmiiboBridge.cs b/src/Ryujinx.HLE/Kenjinx/AmiiboBridge.cs index f795fb727..27cf12e5b 100644 --- a/src/Ryujinx.HLE/Kenjinx/AmiiboBridge.cs +++ b/src/Ryujinx.HLE/Kenjinx/AmiiboBridge.cs @@ -18,13 +18,13 @@ namespace Ryujinx.HLE.Kenjinx // --- TRY 0: Our conflict-free shim class first (recommended) --- // Type name including assembly: Ryujinx.HLE - var shimType = Type.GetType( + Type? shimType = Type.GetType( "Ryujinx.HLE.HOS.Services.Nfc.Nfp.KenjinxAmiiboShim, Ryujinx.HLE", throwOnError: false ); if (shimType != null) { - var m = shimType.GetMethod( + MethodInfo? m = shimType.GetMethod( "InjectAmiibo", BindingFlags.Public | BindingFlags.Static, binder: null, @@ -34,7 +34,7 @@ namespace Ryujinx.HLE.Kenjinx if (m != null) { - var ok = (bool)(m.Invoke(null, new object[] { data }) ?? false); + bool ok = (bool)(m.Invoke(null, new object[] { data }) ?? false); if (ok) { message = "Injected via KenjinxAmiiboShim.InjectAmiibo"; @@ -45,13 +45,13 @@ namespace Ryujinx.HLE.Kenjinx // --- TRY 0.5: If available – static API directly on NfpManager --- // (Only if you later add a static InjectAmiibo(...) method to NfpManager.) - var nfpManagerType = Type.GetType( + Type? nfpManagerType = Type.GetType( "Ryujinx.HLE.HOS.Services.Nfc.Nfp.NfpManager, Ryujinx.HLE", throwOnError: false ); if (nfpManagerType != null) { - var m = nfpManagerType.GetMethod( + MethodInfo? m = nfpManagerType.GetMethod( "InjectAmiibo", BindingFlags.Public | BindingFlags.Static, binder: null, @@ -61,15 +61,15 @@ namespace Ryujinx.HLE.Kenjinx if (m != null) { - var ok = m.Invoke(null, new object[] { data }); + object? ok = m.Invoke(null, new object[] { data }); message = "Injected via NfpManager.InjectAmiibo(static)"; return true; } } // --- TRY 1: Direct access to an existing manager in the system object (your existing code) --- - var sys = device.System; - var nfpMgr = + HOS.Horizon? sys = device.System; + object? nfpMgr = GetField(sys, "NfpManager") ?? GetField(sys, "_nfpManager") ?? GetField(sys, "NfcManager") ?? @@ -78,7 +78,7 @@ namespace Ryujinx.HLE.Kenjinx if (nfpMgr != null) { // Possible method identifiers depending on the tree: - var mi = + MethodInfo? mi = GetMethod(nfpMgr, "InjectAmiibo", new[] { typeof(byte[]) }) ?? GetMethod(nfpMgr, "LoadAmiiboFromBytes", new[] { typeof(byte[]) }) ?? GetMethod(nfpMgr, "LoadVirtualAmiibo", new[] { typeof(byte[]) }) ?? @@ -101,7 +101,7 @@ namespace Ryujinx.HLE.Kenjinx if (device?.System is null) return; // --- Clear via Shim (if present) --- - var shimType = Type.GetType( + Type? shimType = Type.GetType( "Ryujinx.HLE.HOS.Services.Nfc.Nfp.KenjinxAmiiboShim, Ryujinx.HLE", throwOnError: false ); @@ -110,7 +110,7 @@ namespace Ryujinx.HLE.Kenjinx ?.Invoke(null, null); // --- Optional: Static clear API on NfpManager (if available) --- - var nfpManagerType = Type.GetType( + Type? nfpManagerType = Type.GetType( "Ryujinx.HLE.HOS.Services.Nfc.Nfp.NfpManager, Ryujinx.HLE", throwOnError: false ); @@ -119,8 +119,8 @@ namespace Ryujinx.HLE.Kenjinx ?.Invoke(null, null); // --- Your existing instance fallback --- - var sys = device.System; - var nfpMgr = + HOS.Horizon? sys = device.System; + object? nfpMgr = GetField(sys, "NfpManager") ?? GetField(sys, "_nfpManager") ?? GetField(sys, "NfcManager") ?? @@ -128,7 +128,7 @@ namespace Ryujinx.HLE.Kenjinx if (nfpMgr != null) { - var mi = + MethodInfo? mi = GetMethod(nfpMgr, "ClearAmiibo", Type.EmptyTypes) ?? GetMethod(nfpMgr, "ResetVirtualAmiibo", Type.EmptyTypes); @@ -138,14 +138,14 @@ namespace Ryujinx.HLE.Kenjinx private static object? GetField(object target, string name) { - var t = target.GetType(); - var f = t.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); + Type t = target.GetType(); + FieldInfo? f = t.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); return f?.GetValue(target); } private static MethodInfo? GetMethod(object target, string name, Type[]? sig) { - var t = target.GetType(); + Type t = target.GetType(); return t.GetMethod( name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy, diff --git a/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs b/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs index 83380ff45..293e5f846 100644 --- a/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs +++ b/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs @@ -76,7 +76,7 @@ namespace Ryujinx.HLE.Loaders.Executables { reader.GetSegmentSize(segmentType, out int uncompressedSize).ThrowIfFailure(); - var span = program.AsSpan((int)offset, uncompressedSize); + Span span = program.AsSpan((int)offset, uncompressedSize); reader.ReadSegment(segmentType, span).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs b/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs index 83ad5d7e8..637728cef 100644 --- a/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs +++ b/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs @@ -65,7 +65,7 @@ namespace Ryujinx.HLE.Loaders.Executables { reader.GetSegmentSize(segmentType, out uint uncompressedSize).ThrowIfFailure(); - var span = Program.AsSpan((int)offset, (int)uncompressedSize); + Span span = Program.AsSpan((int)offset, (int)uncompressedSize); reader.ReadSegment(segmentType, span).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs b/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs index cf316b565..d457682cf 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs @@ -25,7 +25,7 @@ namespace Ryujinx.HLE.Loaders.Mods ReadOnlySpan ips32TailMagic = "EEOF"u8; MemPatch patches = new(); - var header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan(); + Span header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan(); if (header.Length != ipsHeaderMagic.Length) { @@ -94,7 +94,7 @@ namespace Ryujinx.HLE.Loaders.Mods } else // Copy mode { - var patch = reader.ReadBytes(patchSize); + byte[] patch = reader.ReadBytes(patchSize); if (patch.Length != patchSize) { diff --git a/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs b/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs index bd9b536f0..276f8244f 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs @@ -200,7 +200,7 @@ namespace Ryujinx.HLE.Loaders.Mods } else if (line.StartsWith("@flag")) { - var tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); + string[] tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length < 2) { @@ -234,7 +234,7 @@ namespace Ryujinx.HLE.Loaders.Mods continue; } - var tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); + string[] tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length < 2 || !int.TryParse(tokens[0], System.Globalization.NumberStyles.HexNumber, null, out int offset)) @@ -253,12 +253,12 @@ namespace Ryujinx.HLE.Loaders.Mods if (tokens[1][0] == '"') { - var patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0"); + byte[] patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0"); patches.Add((uint)offset, patch); } else { - var patch = Hex2ByteArrayBE(tokens[1]); + byte[] patch = Hex2ByteArrayBE(tokens[1]); patches.Add((uint)offset, patch); } } diff --git a/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs b/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs index 9b95a23c9..61a52961b 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs @@ -46,7 +46,7 @@ namespace Ryujinx.HLE.Loaders.Mods return; } - foreach (var (patchOffset, patch) in patches._patches) + foreach ((uint patchOffset, byte[] patch) in patches._patches) { _patches[patchOffset] = patch; } @@ -66,7 +66,7 @@ namespace Ryujinx.HLE.Loaders.Mods public int Patch(Span memory, int protectedOffset = 0) { int count = 0; - foreach (var (offset, patch) in _patches.OrderBy(item => item.Key)) + foreach ((uint offset, byte[] patch) in _patches.OrderBy(item => item.Key)) { int patchOffset = (int)offset; int patchSize = patch.Length; diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs index ebe5fefcc..0fcb1c45a 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs @@ -59,7 +59,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions Logger.Info?.Print(LogClass.Loader, $"Loading {name}..."); - using var nsoFile = new UniqueRef(); + using UniqueRef nsoFile = new(); exeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs index e3ae9bf5f..140be91b5 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs @@ -12,7 +12,7 @@ namespace Ryujinx.HLE.Loaders.Processes public static ProcessResult Load(this LocalFileSystem exeFs, Switch device, string romFsPath = "") { MetaLoader metaLoader = exeFs.GetNpdm(); - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new(1); ulong programId = metaLoader.GetProgramId(); device.Configuration.VirtualFileSystem.ModLoader.CollectMods([programId]); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs index 92e71cb5a..f6dab1583 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs @@ -12,21 +12,21 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions { public static ulong GetProgramId(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return npdm.Aci.ProgramId.Value; } public static string GetProgramName(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return StringUtils.Utf8ZToString(npdm.Meta.ProgramName); } public static bool IsProgram64Bit(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return (npdm.Meta.Flags & 1) != 0; } @@ -45,7 +45,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions path = ProcessConst.MainNpdmPath; } - using var npdmFile = new UniqueRef(); + using UniqueRef npdmFile = new(); fileSystem.OpenFile(ref npdmFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs index 2928ac7fe..5db435cf4 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs @@ -49,7 +49,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions ModLoader.GetSdModsBasePath()); // Load Nacp file. - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new(1); if (controlNca != null) { @@ -210,9 +210,9 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static BlitStruct GetNacp(this Nca controlNca, Switch device) { - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new(1); - using var controlFile = new UniqueRef(); + using UniqueRef controlFile = new(); Result result = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel) .OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read); @@ -232,7 +232,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static Cnmt GetCnmt(this Nca cnmtNca, IntegrityCheckLevel checkLevel, ContentMetaType metaType) { string path = $"/{metaType}_{cnmtNca.Header.TitleId:x16}.cnmt"; - using var cnmtFile = new UniqueRef(); + using UniqueRef cnmtFile = new(); try { diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs index 43e0d58e5..073daeea3 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs @@ -28,7 +28,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions { fileSystem.ImportTickets(partitionFileSystem); - var programs = new Dictionary(); + Dictionary programs = new(); foreach (DirectoryEntryEx fileEntry in partitionFileSystem.EnumerateEntries("/", "*.cnmt.nca")) { @@ -152,7 +152,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static Nca GetNca(this IFileSystem fileSystem, KeySet keySet, string path) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); fileSystem.OpenFile(ref ncaFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs index c7d3a499d..9d6050c09 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs @@ -176,7 +176,7 @@ namespace Ryujinx.HLE.Loaders.Processes public bool LoadNxo(string path) { - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new(1); IFileSystem dummyExeFs = null; Stream romfsStream = null; @@ -287,7 +287,7 @@ namespace Ryujinx.HLE.Loaders.Processes public bool LoadNxo(Stream stream, bool isNro, string name) { - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new(1); IFileSystem dummyExeFs = null; Stream romfsStream = null; diff --git a/src/Ryujinx.HLE/UI/Input/NpadReader.cs b/src/Ryujinx.HLE/UI/Input/NpadReader.cs index 9f05827e2..8d26cf440 100644 --- a/src/Ryujinx.HLE/UI/Input/NpadReader.cs +++ b/src/Ryujinx.HLE/UI/Input/NpadReader.cs @@ -1,5 +1,6 @@ using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad; +using System; namespace Ryujinx.HLE.UI.Input { @@ -29,7 +30,7 @@ namespace Ryujinx.HLE.UI.Input { NpadButton buttons = 0; - foreach (var state in _lastStates) + foreach (NpadCommonState state in _lastStates) { buttons |= state.Buttons; } @@ -73,10 +74,10 @@ namespace Ryujinx.HLE.UI.Input { const int MaxEntries = 1024; - ref var npadState = ref _device.Hid.SharedMemory.Npads[npadIndex]; - ref var lastEntry = ref _lastStates[npadIndex]; + ref NpadState npadState = ref _device.Hid.SharedMemory.Npads[npadIndex]; + ref NpadCommonState lastEntry = ref _lastStates[npadIndex]; - var fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries); + ReadOnlySpan> fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries); int firstEntryNum; @@ -94,7 +95,7 @@ namespace Ryujinx.HLE.UI.Input for (; firstEntryNum >= 0; firstEntryNum--) { - var entry = fullKeyEntries[firstEntryNum]; + AtomicStorage entry = fullKeyEntries[firstEntryNum]; // The interval of valid entries should be contiguous. if (entry.SamplingNumber < lastEntry.SamplingNumber) diff --git a/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs b/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs index e2a214da1..fb9040f1a 100644 --- a/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs +++ b/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs @@ -27,7 +27,7 @@ namespace Ryujinx.HLE.Utilities } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); Result initResult = pfsTemp.Initialize(stream.AsStorage()); if (throwOnFailure) diff --git a/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs b/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs index c61e73a29..24ad29aaf 100644 --- a/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs +++ b/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs @@ -63,7 +63,7 @@ namespace Ryujinx.Horizon.Generators.Hipc if (syntaxReceiver != null) { - foreach (var commandInterface in syntaxReceiver.CommandInterfaces) + foreach (CommandInterface commandInterface in syntaxReceiver.CommandInterfaces) { if (!NeedsIServiceObjectImplementation(context.Compilation, commandInterface.ClassDeclarationSyntax)) { @@ -88,7 +88,7 @@ namespace Ryujinx.Horizon.Generators.Hipc GenerateMethodTable(generator, context.Compilation, commandInterface); - foreach (var method in commandInterface.CommandImplementations) + foreach (MethodDeclarationSyntax method in commandInterface.CommandImplementations) { generator.AppendLine(); @@ -131,9 +131,9 @@ namespace Ryujinx.Horizon.Generators.Hipc { generator.EnterScope($"return FrozenDictionary.ToFrozenDictionary(new []"); - foreach (var method in commandInterface.CommandImplementations) + foreach (MethodDeclarationSyntax method in commandInterface.CommandImplementations) { - foreach (var commandId in GetAttributeArguments(compilation, method, TypeCommandAttribute, 0)) + foreach (string commandId in GetAttributeArguments(compilation, method, TypeCommandAttribute, 0)) { string[] args = new string[method.ParameterList.Parameters.Count]; @@ -145,7 +145,7 @@ namespace Ryujinx.Horizon.Generators.Hipc { int index = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { string canonicalTypeName = GetCanonicalTypeNameWithGenericArguments(compilation, parameter.Type); CommandArgType argType = GetCommandArgType(compilation, parameter); @@ -197,7 +197,7 @@ namespace Ryujinx.Horizon.Generators.Hipc if (symbol != null) { - foreach (var attribute in symbol.GetAttributes()) + foreach (AttributeData attribute in symbol.GetAttributes()) { if (attribute.AttributeClass?.ToDisplayString() == attributeName && (uint)argIndex < (uint)attribute.ConstructorArguments.Length) @@ -219,7 +219,7 @@ namespace Ryujinx.Horizon.Generators.Hipc int outObjectsCount = 0; int buffersCount = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { if (IsObject(compilation, parameter)) { @@ -293,7 +293,7 @@ namespace Ryujinx.Horizon.Generators.Hipc int inMoveHandleIndex = 0; int inObjectIndex = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { string name = parameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -776,9 +776,9 @@ namespace Ryujinx.Horizon.Generators.Hipc private static bool HasAttribute(Compilation compilation, ParameterSyntax parameterSyntax, string fullAttributeName) { - foreach (var attributeList in parameterSyntax.AttributeLists) + foreach (AttributeListSyntax attributeList in parameterSyntax.AttributeLists) { - foreach (var attribute in attributeList.Attributes) + foreach (AttributeSyntax attribute in attributeList.Attributes) { if (GetCanonicalTypeName(compilation, attribute) == fullAttributeName) { @@ -793,8 +793,8 @@ namespace Ryujinx.Horizon.Generators.Hipc private static bool NeedsIServiceObjectImplementation(Compilation compilation, ClassDeclarationSyntax classDeclarationSyntax) { ITypeSymbol type = compilation.GetSemanticModel(classDeclarationSyntax.SyntaxTree).GetDeclaredSymbol(classDeclarationSyntax); - var serviceObjectInterface = type?.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == TypeIServiceObject); - var interfaceMember = serviceObjectInterface?.GetMembers().FirstOrDefault(x => x.Name == "GetCommandHandlers"); + INamedTypeSymbol serviceObjectInterface = type?.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == TypeIServiceObject); + ISymbol interfaceMember = serviceObjectInterface?.GetMembers().FirstOrDefault(x => x.Name == "GetCommandHandlers"); // Return true only if the class implements IServiceObject but does not actually implement the method // that the interface defines, since this is the only case we want to handle, if the method already exists diff --git a/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs b/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs index 5682e2829..858b4a2a5 100644 --- a/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs +++ b/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Horizon.Generators.Hipc CommandInterface commandInterface = new(classDeclaration); - foreach (var memberDeclaration in classDeclaration.Members) + foreach (MemberDeclarationSyntax memberDeclaration in classDeclaration.Members) { if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) { @@ -44,7 +44,7 @@ namespace Ryujinx.Horizon.Generators.Hipc if (methodDeclaration.AttributeLists.Count != 0) { - foreach (var attributeList in methodDeclaration.AttributeLists) + foreach (AttributeListSyntax attributeList in methodDeclaration.AttributeLists) { if (attributeList.Attributes.Any(x => x.Name.ToString().Contains(attributeName))) { diff --git a/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs b/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs index 430b1dc94..68712dfa9 100644 --- a/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs +++ b/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Horizon.Kernel.Generators if (syntaxReceiver != null) { - foreach (var method in syntaxReceiver.SvcImplementations) + foreach (MethodDeclarationSyntax method in syntaxReceiver.SvcImplementations) { GenerateMethod32(generator, context.Compilation, method); GenerateMethod64(generator, context.Compilation, method); @@ -214,7 +214,7 @@ namespace Ryujinx.Horizon.Kernel.Generators List logInArgs = []; List logOutArgs = []; - foreach (var methodParameter in method.ParameterList.Parameters) + foreach (ParameterSyntax methodParameter in method.ParameterList.Parameters) { string name = methodParameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -333,7 +333,7 @@ namespace Ryujinx.Horizon.Kernel.Generators List logInArgs = []; List logOutArgs = []; - foreach (var methodParameter in method.ParameterList.Parameters) + foreach (ParameterSyntax methodParameter in method.ParameterList.Parameters) { string name = methodParameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -476,7 +476,7 @@ namespace Ryujinx.Horizon.Kernel.Generators generator.EnterScope($"public static void Dispatch{suffix}(Syscall syscall, {TypeExecutionContext} context, int id)"); generator.EnterScope("switch (id)"); - foreach (var syscall in syscalls) + foreach (SyscallIdAndName syscall in syscalls) { generator.AppendLine($"case {syscall.Id}:"); generator.IncreaseIndentation(); diff --git a/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs b/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs index e25c6317b..abeea4020 100644 --- a/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs +++ b/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Horizon.Kernel.Generators return; } - foreach (var memberDeclaration in classDeclaration.Members) + foreach (MemberDeclarationSyntax memberDeclaration in classDeclaration.Members) { if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) { diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs index 78114c51f..35967d274 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs @@ -39,9 +39,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(1)] public Result CreateDeliveryCacheStorageService(out IDeliveryCacheStorageService service, [ClientProcessId] ulong pid) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new(); - var resultCode = _libHacService.Get.CreateDeliveryCacheStorageService(ref libHacService.Ref, pid); + LibHac.Result resultCode = _libHacService.Get.CreateDeliveryCacheStorageService(ref libHacService.Ref, pid); if (resultCode.IsSuccess()) { @@ -58,9 +58,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(2)] public Result CreateDeliveryCacheStorageServiceWithApplicationId(out IDeliveryCacheStorageService service, ApplicationId applicationId) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new(); - var resultCode = _libHacService.Get.CreateDeliveryCacheStorageServiceWithApplicationId(ref libHacService.Ref, new LibHac.ApplicationId(applicationId.Id)); + LibHac.Result resultCode = _libHacService.Get.CreateDeliveryCacheStorageServiceWithApplicationId(ref libHacService.Ref, new LibHac.ApplicationId(applicationId.Id)); if (resultCode.IsSuccess()) { diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs index ecbc4bdb7..356156fc1 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs @@ -22,9 +22,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(0)] public Result CreateFileService(out IDeliveryCacheFileService service) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new(); - var resultCode = _libHacService.Get.CreateFileService(ref libHacService.Ref); + LibHac.Result resultCode = _libHacService.Get.CreateFileService(ref libHacService.Ref); if (resultCode.IsSuccess()) { @@ -41,9 +41,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(1)] public Result CreateDirectoryService(out IDeliveryCacheDirectoryService service) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new(); - var resultCode = _libHacService.Get.CreateDirectoryService(ref libHacService.Ref); + LibHac.Result resultCode = _libHacService.Get.CreateDirectoryService(ref libHacService.Ref); if (resultCode.IsSuccess()) { diff --git a/src/Ryujinx.Horizon/HeapAllocator.cs b/src/Ryujinx.Horizon/HeapAllocator.cs index a9152f795..522387631 100644 --- a/src/Ryujinx.Horizon/HeapAllocator.cs +++ b/src/Ryujinx.Horizon/HeapAllocator.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Horizon { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -103,7 +103,7 @@ namespace Ryujinx.Horizon private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -116,7 +116,7 @@ namespace Ryujinx.Horizon private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { diff --git a/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs b/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs index b11318fe5..d8a79cbc8 100644 --- a/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs +++ b/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Horizon.Sdk.Arp { if (_sessionHandle == 0) { - using var smApi = new SmApi(); + using SmApi smApi = new(); smApi.Initialize(); smApi.GetServiceHandle(out _sessionHandle, ServiceName.Encode(ArpRName)).AbortOnFailure(); diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs index d5d047201..b190cb8ae 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs @@ -5,6 +5,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk.Audio.Detail @@ -49,7 +50,7 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan name, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ResultCode rc = _impl.OpenAudioIn( out string outputDeviceName, diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs index 3d129470c..facfbbc03 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs @@ -5,6 +5,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk.Audio.Detail @@ -49,7 +50,7 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan name, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ResultCode rc = _impl.OpenAudioOut( out string outputDeviceName, diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs index 48693fd14..e7eedeccd 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs @@ -4,6 +4,7 @@ using Ryujinx.Common.Logging; using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; +using Ryujinx.Memory; namespace Ryujinx.Horizon.Sdk.Audio.Detail { @@ -30,11 +31,11 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail AppletResourceUserId appletResourceId, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ulong workBufferAddress = HorizonStatic.Syscall.GetTransferMemoryAddress(workBufferHandle); Result result = new((int)_impl.OpenAudioRenderer( - out var renderSystem, + out AudioRenderSystem renderSystem, clientMemoryManager, ref parameter.Configuration, appletResourceId.Id, @@ -96,10 +97,10 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail AppletResourceUserId appletResourceId, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); Result result = new((int)_impl.OpenAudioRenderer( - out var renderSystem, + out AudioRenderSystem renderSystem, clientMemoryManager, ref parameter.Configuration, appletResourceId.Id, diff --git a/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs b/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs index a5622d4aa..e55dd75be 100644 --- a/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs +++ b/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Horizon.Sdk.Lbl public LblApi() { - using var smApi = new SmApi(); + using SmApi smApi = new(); smApi.Initialize(); smApi.GetServiceHandle(out _sessionHandle, ServiceName.Encode(LblName)).AbortOnFailure(); diff --git a/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs b/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs index fc5cd683d..899ea57f5 100644 --- a/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs +++ b/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs @@ -35,13 +35,13 @@ namespace Ryujinx.Horizon.Sdk.Ngc.Detail { get { - var ranges = GetBitfieldRanges(); + ReadOnlySpan ranges = GetBitfieldRanges(); int rangeBlockIndex = index / CompressedEntriesPerBlock; if (rangeBlockIndex < ranges.Length) { - var range = ranges[rangeBlockIndex]; + BitfieldRange range = ranges[rangeBlockIndex]; int bitfieldLength = range.BitfieldLength; int bitfieldOffset = (index % CompressedEntriesPerBlock) * bitfieldLength; diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs index 8fac94abe..701db76e0 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes public static void DestroySystemEvent(ref SystemEventType sysEvent) { - var oldState = sysEvent.State; + SystemEventType.InitializationState oldState = sysEvent.State; sysEvent.State = SystemEventType.InitializationState.NotInitialized; switch (oldState) diff --git a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs index 5527c1e35..b5bf853b3 100644 --- a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs +++ b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs @@ -1,6 +1,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Sf.Cmif; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk @@ -12,7 +13,7 @@ namespace Ryujinx.Horizon.Sdk ulong tlsAddress = HorizonStatic.ThreadContext.TlsAddress; int tlsSize = Api.TlsMessageBufferSize; - using (var tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) + using (WritableRegion tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) { CmifRequest request = CmifMessage.CreateRequest(tlsRegion.Memory.Span, new CmifRequestFormat { @@ -48,7 +49,7 @@ namespace Ryujinx.Horizon.Sdk ulong tlsAddress = HorizonStatic.ThreadContext.TlsAddress; int tlsSize = Api.TlsMessageBufferSize; - using (var tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) + using (WritableRegion tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) { CmifRequestFormat format = new() { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs index 58957a701..2e7879f2d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return SfResult.InvalidHeaderSize; } - var inHeader = MemoryMarshal.Cast(inRawData)[0]; + CmifDomainInHeader inHeader = MemoryMarshal.Cast(inRawData)[0]; ReadOnlySpan inDomainRawData = inRawData[Unsafe.SizeOf()..]; @@ -28,7 +28,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif switch (inHeader.Type) { case CmifDomainRequestType.SendMessage: - var targetObject = domain.GetObject(targetObjectId); + ServiceObjectHolder targetObject = domain.GetObject(targetObjectId); if (targetObject == null) { return SfResult.TargetNotFound; @@ -48,7 +48,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif int[] inObjectIds = new int[inHeader.ObjectsCount]; - var domainProcessor = new DomainServiceObjectProcessor(domain, inObjectIds); + DomainServiceObjectProcessor domainProcessor = new(domain, inObjectIds); if (context.Processor == null) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs index f677e0598..f99584610 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs @@ -44,7 +44,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServerMessageRuntimeMetadata GetRuntimeMetadata() { - var runtimeMetadata = _implProcessor.GetRuntimeMetadata(); + ServerMessageRuntimeMetadata runtimeMetadata = _implProcessor.GetRuntimeMetadata(); return new ServerMessageRuntimeMetadata( (ushort)(runtimeMetadata.InDataSize + runtimeMetadata.InObjectsCount * sizeof(int)), @@ -84,7 +84,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override HipcMessageData PrepareForReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { - var response = _implProcessor.PrepareForReply(ref context, out outRawData, runtimeMetadata); + HipcMessageData response = _implProcessor.PrepareForReply(ref context, out outRawData, runtimeMetadata); int outHeaderSize = Unsafe.SizeOf(); int implOutDataTotalSize = ImplOutDataTotalSize; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs index 75b157d91..2f8e355a4 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return null; } - var entry = _freeList.First?.Value; + Entry entry = _freeList.First?.Value; _freeList.RemoveFirst(); return entry; } @@ -92,7 +92,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServiceObjectHolder GetObject(int id) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); if (entry == null) { return null; @@ -116,7 +116,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override void RegisterObject(int id, ServiceObjectHolder obj) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); lock (_manager._entryOwnerLock) { @@ -131,7 +131,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { for (int i = 0; i < outIds.Length; i++) { - var entry = _manager._entryManager.AllocateEntry(); + EntryManager.Entry entry = _manager._entryManager.AllocateEntry(); if (entry == null) { return SfResult.OutOfDomainEntries; @@ -147,7 +147,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServiceObjectHolder UnregisterObject(int id) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); if (entry == null) { return null; @@ -184,7 +184,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { for (int i = 0; i < ids.Length; i++) { - var entry = _manager._entryManager.GetEntry(ids[i]); + EntryManager.Entry entry = _manager._entryManager.GetEntry(ids[i]); _manager._entryManager.FreeEntry(entry); } @@ -192,7 +192,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public void Dispose() { - foreach (var entry in _entries) + foreach (EntryManager.Entry entry in _entries) { if (entry.Obj.ServiceObject is IDisposable disposableObj) { @@ -225,7 +225,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return null; } - var domain = new Domain(this); + Domain domain = new(this); _domains.Add(domain); return domain; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs index 70a0db58d..23ef0fd23 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs @@ -35,9 +35,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif ReadOnlySpan inMessageRawData = inRawData[Unsafe.SizeOf()..]; uint commandId = inHeader.CommandId; - var outHeader = Span.Empty; + Span outHeader = Span.Empty; - if (!entries.TryGetValue((int)commandId, out var commandHandler)) + if (!entries.TryGetValue((int)commandId, out CommandHandler commandHandler)) { if (HorizonStatic.Options.IgnoreMissingServices) { @@ -86,7 +86,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif private static void PrepareForStubReply(scoped ref ServiceDispatchContext context, out Span outRawData) { - var response = HipcMessage.WriteResponse(context.OutMessageBuffer, 0, 0x20 / sizeof(uint), 0, 0); + HipcMessageData response = HipcMessage.WriteResponse(context.OutMessageBuffer, 0, 0x20 / sizeof(uint), 0, 0); outRawData = MemoryMarshal.Cast(response.DataWords); } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs index d0efe0d4b..3dcf4a263 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Horizon.Sdk.Sf context.Processor.SetImplementationProcessor(_processor); } - var runtimeMetadata = context.Processor.GetRuntimeMetadata(); + ServerMessageRuntimeMetadata runtimeMetadata = context.Processor.GetRuntimeMetadata(); Result result = context.Processor.PrepareForProcess(ref context, runtimeMetadata); return result.IsFailure ? result : _invoke(ref context, _processor, runtimeMetadata, inRawData, ref outHeader); diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs index 7f5284648..53bbe56f9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public static ref T GetRef(PointerAndSize bufferRange) where T : unmanaged { - var writableRegion = GetWritableRegion(bufferRange); + WritableRegion writableRegion = GetWritableRegion(bufferRange); return ref MemoryMarshal.Cast(writableRegion.Memory.Span)[0]; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs index 5f3f67061..4c8dacb8f 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs @@ -35,7 +35,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc handles[0] = sessionHandle; - var tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); + ReadOnlySpan tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); if (messageBuffer == tlsSpan) { @@ -56,7 +56,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc private static Result ReplyImpl(int sessionHandle, ReadOnlySpan messageBuffer) { - var tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); + ReadOnlySpan tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); if (messageBuffer == tlsSpan) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs index 4f0bbb014..953f9e755 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { objectId = 0; - var domain = _manager.Domain.AllocateDomainServiceObject(); + DomainServiceObject domain = _manager.Domain.AllocateDomainServiceObject(); if (domain == null) { return HipcResult.OutOfDomains; @@ -66,7 +66,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return HipcResult.TargetNotDomain; } - var obj = domain.GetObject(objectId); + ServiceObjectHolder obj = domain.GetObject(objectId); if (obj == null) { return HipcResult.DomainObjectNotFound; @@ -100,7 +100,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { clientHandle = 0; - var clone = _session.ServiceObjectHolder.Clone(); + ServiceObjectHolder clone = _session.ServiceObjectHolder.Clone(); if (clone == null) { return HipcResult.DomainObjectNotFound; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs index 31ca264e3..669dc5ee3 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs @@ -2,6 +2,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.OsTypes; using Ryujinx.Horizon.Sdk.Sf.Cmif; using Ryujinx.Horizon.Sdk.Sm; +using Ryujinx.Memory; using System; using System.Linq; using System.Threading; @@ -257,14 +258,14 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc ServerSession session = (ServerSession)holder; - using var tlsMessage = HorizonStatic.AddressSpace.GetWritableRegion(HorizonStatic.ThreadContext.TlsAddress, Api.TlsMessageBufferSize); + using WritableRegion tlsMessage = HorizonStatic.AddressSpace.GetWritableRegion(HorizonStatic.ThreadContext.TlsAddress, Api.TlsMessageBufferSize); Result result; if (_canDeferInvokeRequest) { // If the request is deferred, we save the message on a temporary buffer to process it later. - using var savedMessage = HorizonStatic.AddressSpace.GetWritableRegion(session.SavedMessage.Address, (int)session.SavedMessage.Size); + using WritableRegion savedMessage = HorizonStatic.AddressSpace.GetWritableRegion(session.SavedMessage.Address, (int)session.SavedMessage.Size); DebugUtil.Assert(tlsMessage.Memory.Length == savedMessage.Memory.Length); diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs index bd5a48444..f51e0811e 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs @@ -186,7 +186,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { CommandType commandType = GetCmifCommandType(inMessage); - using var _ = new ScopedInlineContextChange(GetInlineContext(commandType, inMessage)); + using ScopedInlineContextChange _ = new(GetInlineContext(commandType, inMessage)); return commandType switch { @@ -282,7 +282,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return HipcResult.InvalidRequestSize; } - var dispatchCtx = new ServiceDispatchContext + ServiceDispatchContext dispatchCtx = new() { ServiceObject = objectHolder.ServiceObject, Manager = this, @@ -312,7 +312,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc result = Api.Reply(session.SessionHandle, outMessage); - ref var handlesToClose = ref dispatchCtx.HandlesToClose; + ref HandlesToClose handlesToClose = ref dispatchCtx.HandlesToClose; for (int i = 0; i < handlesToClose.Count; i++) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs index 7b6e85654..7b903b143 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Horizon.Sdk.Sf switch (argInfo.Type) { case CommandArgType.Buffer: - var flags = argInfo.BufferFlags; + HipcBufferFlags flags = argInfo.BufferFlags; if ((flags & HipcBufferFlags.In) != 0) { @@ -146,7 +146,7 @@ namespace Ryujinx.Horizon.Sdk.Sf continue; } - var flags = _args[i].BufferFlags; + HipcBufferFlags flags = _args[i].BufferFlags; bool isMapAlias; if ((flags & HipcBufferFlags.MapAlias) != 0) @@ -159,7 +159,7 @@ namespace Ryujinx.Horizon.Sdk.Sf } else /* if (flags & HipcBufferFlags.HipcAutoSelect)) */ { - var descriptor = (flags & HipcBufferFlags.In) != 0 + HipcBufferDescriptor descriptor = (flags & HipcBufferFlags.In) != 0 ? context.Request.Data.SendBuffers[sendMapAliasIndex] : context.Request.Data.ReceiveBuffers[recvMapAliasIndex]; @@ -170,7 +170,7 @@ namespace Ryujinx.Horizon.Sdk.Sf if (isMapAlias) { - var descriptor = (flags & HipcBufferFlags.In) != 0 + HipcBufferDescriptor descriptor = (flags & HipcBufferFlags.In) != 0 ? context.Request.Data.SendBuffers[sendMapAliasIndex++] : context.Request.Data.ReceiveBuffers[recvMapAliasIndex++]; @@ -185,7 +185,7 @@ namespace Ryujinx.Horizon.Sdk.Sf { if ((flags & HipcBufferFlags.In) != 0) { - var descriptor = context.Request.Data.SendStatics[sendPointerIndex++]; + HipcStaticDescriptor descriptor = context.Request.Data.SendStatics[sendPointerIndex++]; ulong address = descriptor.Address; ulong size = descriptor.Size; @@ -206,8 +206,8 @@ namespace Ryujinx.Horizon.Sdk.Sf } else { - var data = MemoryMarshal.Cast(context.Request.Data.DataWordsPadded); - var recvPointerSizes = MemoryMarshal.Cast(data[runtimeMetadata.UnfixedOutPointerSizeOffset..]); + Span data = MemoryMarshal.Cast(context.Request.Data.DataWordsPadded); + Span recvPointerSizes = MemoryMarshal.Cast(data[runtimeMetadata.UnfixedOutPointerSizeOffset..]); size = recvPointerSizes[unfixedRecvPointerIndex++]; } @@ -257,13 +257,13 @@ namespace Ryujinx.Horizon.Sdk.Sf continue; } - var flags = _args[i].BufferFlags; + HipcBufferFlags flags = _args[i].BufferFlags; if ((flags & HipcBufferFlags.Out) == 0) { continue; } - var buffer = _bufferRanges[i]; + PointerAndSize buffer = _bufferRanges[i]; if ((flags & HipcBufferFlags.Pointer) != 0) { @@ -303,7 +303,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override Result PrepareForProcess(ref ServiceDispatchContext context, ServerMessageRuntimeMetadata runtimeMetadata) { - ref var meta = ref context.Request.Meta; + ref HipcMetadata meta = ref context.Request.Meta; bool requestValid = true; requestValid &= meta.SendPid == _hasInProcessIdHolder; requestValid &= meta.SendStaticsCount == _inPointerBuffersCount; @@ -346,7 +346,7 @@ namespace Ryujinx.Horizon.Sdk.Sf } int index = inObjectIndex++; - var inObject = inObjects[index]; + ServiceObjectHolder inObject = inObjects[index]; objects[index] = inObject?.ServiceObject; } @@ -362,7 +362,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override HipcMessageData PrepareForReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { int rawDataSize = OutRawDataSize + runtimeMetadata.OutHeadersSize; - var response = HipcMessage.WriteResponse( + HipcMessageData response = HipcMessage.WriteResponse( context.OutMessageBuffer, _outPointerBuffersCount, (BitUtils.AlignUp(rawDataSize, 4) + 0x10) / sizeof(uint), @@ -376,7 +376,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override void PrepareForErrorReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { int rawDataSize = runtimeMetadata.OutHeadersSize; - var response = HipcMessage.WriteResponse( + HipcMessageData response = HipcMessage.WriteResponse( context.OutMessageBuffer, 0, (BitUtils.AlignUp(rawDataSize, 4) + 0x10) / sizeof(uint), diff --git a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs index 177cc0d3d..c13b85c4c 100644 --- a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs +++ b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs @@ -120,7 +120,7 @@ namespace Ryujinx.Horizon.Sm.Impl return SmResult.NotRegistered; } - ref var serviceInfo = ref _services[serviceIndex]; + ref ServiceInfo serviceInfo = ref _services[serviceIndex]; if (serviceInfo.OwnerProcessId != processId) { return SmResult.NotAllowed; diff --git a/src/Ryujinx.Input.SDL3/SDL3GamepadDriver.cs b/src/Ryujinx.Input.SDL3/SDL3GamepadDriver.cs index 2645063c4..3f858f8a2 100644 --- a/src/Ryujinx.Input.SDL3/SDL3GamepadDriver.cs +++ b/src/Ryujinx.Input.SDL3/SDL3GamepadDriver.cs @@ -248,17 +248,17 @@ namespace Ryujinx.Input.SDL3 SDL3Driver.Instance.OnJoystickDisconnected -= HandleJoyStickDisconnected; // Simulate a full disconnect when disposing - foreach (var gamepad in _gamepadsIds) + foreach (KeyValuePair gamepad in _gamepadsIds) { OnGamepadDisconnected?.Invoke(gamepad.Value); } - foreach (var gamepad in _joyConsIds) + foreach (KeyValuePair gamepad in _joyConsIds) { OnGamepadDisconnected?.Invoke(gamepad.Value); } - foreach (var gamepad in _linkedJoyConsIds) + foreach (KeyValuePair gamepad in _linkedJoyConsIds) { OnGamepadDisconnected?.Invoke(gamepad.Value); } @@ -331,7 +331,7 @@ namespace Ryujinx.Input.SDL3 { lock (_gamepadsIds) { - foreach (var gamepad in _gamepadsIds) + foreach (KeyValuePair gamepad in _gamepadsIds) { yield return GetGamepad(gamepad.Value); } @@ -339,7 +339,7 @@ namespace Ryujinx.Input.SDL3 lock (_joyConsIds) { - foreach (var gamepad in _joyConsIds) + foreach (KeyValuePair gamepad in _joyConsIds) { yield return GetGamepad(gamepad.Value); } @@ -347,7 +347,7 @@ namespace Ryujinx.Input.SDL3 lock (_linkedJoyConsIds) { - foreach (var gamepad in _linkedJoyConsIds) + foreach (KeyValuePair gamepad in _linkedJoyConsIds) { yield return GetGamepad(gamepad.Value); } diff --git a/src/Ryujinx.Input.SDL3/SDL3JoyCon.cs b/src/Ryujinx.Input.SDL3/SDL3JoyCon.cs index 4c6326ca3..5e40de5e0 100644 --- a/src/Ryujinx.Input.SDL3/SDL3JoyCon.cs +++ b/src/Ryujinx.Input.SDL3/SDL3JoyCon.cs @@ -366,7 +366,7 @@ namespace Ryujinx.Input.SDL3 if (HasConfiguration) { - var joyconStickConfig = GetLogicalJoyStickConfig(inputId); + JoyconConfigControllerStick joyconStickConfig = GetLogicalJoyStickConfig(inputId); if (joyconStickConfig != null) { diff --git a/src/Ryujinx.Input.SDL3/SDL3JoyConPair.cs b/src/Ryujinx.Input.SDL3/SDL3JoyConPair.cs index e116f1272..e176cea1d 100644 --- a/src/Ryujinx.Input.SDL3/SDL3JoyConPair.cs +++ b/src/Ryujinx.Input.SDL3/SDL3JoyConPair.cs @@ -98,7 +98,7 @@ namespace Ryujinx.Input.SDL3 string matchName = isLeft ? SDL3JoyCon.RightName : SDL3JoyCon.LeftName; match = 0; - foreach (var joyConId in joyConIds.Keys) + foreach (SDL_JoystickID joyConId in joyConIds.Keys) { if (SDL_GetGamepadNameForID(joyConId) == matchName) { diff --git a/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs b/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs index 80fed2b82..4c8682da5 100644 --- a/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs +++ b/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs @@ -144,7 +144,7 @@ namespace Ryujinx.Input.Assigner { StringWriter writer = new(); - foreach (var kvp in _stats) + foreach (KeyValuePair kvp in _stats) { writer.WriteLine($"Button {kvp.Key} -> {kvp.Value}"); } diff --git a/src/Ryujinx.Input/HLE/NpadController.cs b/src/Ryujinx.Input/HLE/NpadController.cs index e61c5107d..87cff4334 100644 --- a/src/Ryujinx.Input/HLE/NpadController.cs +++ b/src/Ryujinx.Input/HLE/NpadController.cs @@ -281,7 +281,7 @@ namespace Ryujinx.Input.HLE public void Update() { // _gamepad may be altered by other threads - var gamepad = _gamepad; + IGamepad gamepad = _gamepad; if (gamepad != null && GamepadDriver != null) { @@ -508,7 +508,7 @@ namespace Ryujinx.Input.HLE public static KeyboardInput GetHLEKeyboardInput(IGamepadDriver KeyboardDriver) { - var keyboard = KeyboardDriver.GetGamepad("0") as IKeyboard; + IKeyboard keyboard = KeyboardDriver.GetGamepad("0") as IKeyboard; KeyboardStateSnapshot keyboardState = keyboard?.GetKeyboardStateSnapshot(); diff --git a/src/Ryujinx.Input/HLE/NpadManager.cs b/src/Ryujinx.Input/HLE/NpadManager.cs index 5b6afe924..07ff15328 100644 --- a/src/Ryujinx.Input/HLE/NpadManager.cs +++ b/src/Ryujinx.Input/HLE/NpadManager.cs @@ -7,6 +7,7 @@ using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Numerics; using System.Runtime.CompilerServices; using System.Threading; using CemuHookClient = Ryujinx.Input.Motion.CemuHook.Client; @@ -60,7 +61,7 @@ namespace Ryujinx.Input.HLE lock (_lock) { List validInputs = new(); - foreach (var inputConfigEntry in _inputConfig) + foreach (InputConfig inputConfigEntry in _inputConfig) { if (_controllers[(int)inputConfigEntry.PlayerIndex] != null) { @@ -238,7 +239,7 @@ namespace Ryujinx.Input.HLE isJoyconPair = inputConfig.ControllerType == ControllerType.JoyconPair; - var altMotionState = isJoyconPair ? controller.GetHLEMotionState(true) : default; + SixAxisInput altMotionState = isJoyconPair ? controller.GetHLEMotionState(true) : default; motionState = (controller.GetHLEMotionState(), altMotionState); } @@ -277,9 +278,9 @@ namespace Ryujinx.Input.HLE if (_enableMouse) { - var mouse = _mouseDriver.GetGamepad("0") as IMouse; + IMouse mouse = _mouseDriver.GetGamepad("0") as IMouse; - var mouseInput = IMouse.GetMouseStateSnapshot(mouse); + MouseStateSnapshot mouseInput = IMouse.GetMouseStateSnapshot(mouse); uint buttons = 0; @@ -310,7 +311,7 @@ namespace Ryujinx.Input.HLE if (mouse != null) { - var position = IMouse.GetScreenPosition(mouseInput.Position, mouse.ClientSize, aspectRatio); + Vector2 position = IMouse.GetScreenPosition(mouseInput.Position, mouse.ClientSize, aspectRatio); _device.Hid.Mouse.Update((int)position.X, (int)position.Y, buttons, (int)mouseInput.Scroll.X, (int)mouseInput.Scroll.Y, true); diff --git a/src/Ryujinx.Input/HLE/TouchScreenManager.cs b/src/Ryujinx.Input/HLE/TouchScreenManager.cs index c613f9281..28d800d18 100644 --- a/src/Ryujinx.Input/HLE/TouchScreenManager.cs +++ b/src/Ryujinx.Input/HLE/TouchScreenManager.cs @@ -2,6 +2,7 @@ using Ryujinx.HLE; using Ryujinx.HLE.HOS.Services.Hid; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.TouchScreen; using System; +using System.Numerics; namespace Ryujinx.Input.HLE { @@ -29,7 +30,7 @@ namespace Ryujinx.Input.HLE if (_wasClicking && !isClicking) { MouseStateSnapshot snapshot = IMouse.GetMouseStateSnapshot(_mouse); - var touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); + Vector2 touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); TouchPoint currentPoint = new() { @@ -58,7 +59,7 @@ namespace Ryujinx.Input.HLE if (aspectRatio > 0) { MouseStateSnapshot snapshot = IMouse.GetMouseStateSnapshot(_mouse); - var touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); + Vector2 touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); TouchAttribute attribute = TouchAttribute.None; diff --git a/src/Ryujinx.Input/Motion/CemuHook/Client.cs b/src/Ryujinx.Input/Motion/CemuHook/Client.cs index e19f3d847..d07ae6431 100644 --- a/src/Ryujinx.Input/Motion/CemuHook/Client.cs +++ b/src/Ryujinx.Input/Motion/CemuHook/Client.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Input.Motion.CemuHook lock (_clients) { - foreach (var client in _clients) + foreach (KeyValuePair client in _clients) { try { @@ -209,7 +209,7 @@ namespace Ryujinx.Input.Motion.CemuHook { client.Client.ReceiveTimeout = timeout; - var result = client?.Receive(ref endPoint); + byte[] result = client?.Receive(ref endPoint); if (result.Length > 0) { @@ -225,7 +225,7 @@ namespace Ryujinx.Input.Motion.CemuHook private void SetRetryTimer(int clientId) { - var elapsedMs = PerformanceCounter.ElapsedMilliseconds; + long elapsedMs = PerformanceCounter.ElapsedMilliseconds; _clientRetryTimer[clientId] = elapsedMs; } @@ -338,9 +338,9 @@ namespace Ryujinx.Input.Motion.CemuHook { int slot = inputData.Shared.Slot; - if (_motionData.TryGetValue(clientId, out var motionDataItem)) + if (_motionData.TryGetValue(clientId, out Dictionary motionDataItem)) { - if (motionDataItem.TryGetValue(slot, out var previousData)) + if (motionDataItem.TryGetValue(slot, out MotionInput previousData)) { previousData.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone); } diff --git a/src/Ryujinx.Memory/AddressSpaceManager.cs b/src/Ryujinx.Memory/AddressSpaceManager.cs index 4b1f57504..81b87d32c 100644 --- a/src/Ryujinx.Memory/AddressSpaceManager.cs +++ b/src/Ryujinx.Memory/AddressSpaceManager.cs @@ -119,13 +119,13 @@ namespace Ryujinx.Memory return []; } - var hostRegions = GetHostRegionsImpl(va, size); + List hostRegions = GetHostRegionsImpl(va, size); if (hostRegions == null) { return null; } - var regions = new MemoryRange[hostRegions.Count]; + MemoryRange[] regions = new MemoryRange[hostRegions.Count]; ulong backingStart = (ulong)_backingMemory.Pointer; ulong backingEnd = backingStart + _backingMemory.Size; @@ -134,7 +134,7 @@ namespace Ryujinx.Memory for (int i = 0; i < regions.Length; i++) { - var hostRegion = hostRegions[i]; + HostMemoryRange hostRegion = hostRegions[i]; if (hostRegion.Address >= backingStart && hostRegion.Address < backingEnd) { @@ -159,7 +159,7 @@ namespace Ryujinx.Memory int pages = GetPagesCount(va, size, out va); - var regions = new List(); + List regions = new(); nuint regionStart = GetHostAddress(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs b/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs index 5fe8d936c..f759b2d98 100644 --- a/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs +++ b/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Memory public BytesReadOnlySequenceSegment Append(Memory memory) { - var nextSegment = new BytesReadOnlySequenceSegment(memory) + BytesReadOnlySequenceSegment nextSegment = new(memory) { RunningIndex = RunningIndex + Memory.Length }; @@ -34,8 +34,8 @@ namespace Ryujinx.Memory /// True if the segments are contiguous, otherwise false public unsafe bool IsContiguousWith(Memory other, out nuint contiguousStart, out int contiguousSize) { - if (MemoryMarshal.TryGetMemoryManager>(Memory, out var thisMemoryManager) && - MemoryMarshal.TryGetMemoryManager>(other, out var otherMemoryManager) && + if (MemoryMarshal.TryGetMemoryManager>(Memory, out NativeMemoryManager thisMemoryManager) && + MemoryMarshal.TryGetMemoryManager>(other, out NativeMemoryManager otherMemoryManager) && thisMemoryManager.Pointer + thisMemoryManager.Length == otherMemoryManager.Pointer) { contiguousStart = (nuint)thisMemoryManager.Pointer; diff --git a/src/Ryujinx.Memory/IVirtualMemoryManager.cs b/src/Ryujinx.Memory/IVirtualMemoryManager.cs index 050c85862..a4d810648 100644 --- a/src/Ryujinx.Memory/IVirtualMemoryManager.cs +++ b/src/Ryujinx.Memory/IVirtualMemoryManager.cs @@ -127,7 +127,7 @@ namespace Ryujinx.Memory { int copySize = (int)Math.Min(MaxChunkSize, size - subOffset); - using var writableRegion = GetWritableRegion(va + subOffset, copySize); + using WritableRegion writableRegion = GetWritableRegion(va + subOffset, copySize); writableRegion.Memory.Span.Fill(value); } diff --git a/src/Ryujinx.Memory/MemoryManagementWindows.cs b/src/Ryujinx.Memory/MemoryManagementWindows.cs index 468355dd0..e5a50f866 100644 --- a/src/Ryujinx.Memory/MemoryManagementWindows.cs +++ b/src/Ryujinx.Memory/MemoryManagementWindows.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Memory public static nint CreateSharedMemory(nint size, bool reserve) { - var prot = reserve ? FileMapProtection.SectionReserve : FileMapProtection.SectionCommit; + FileMapProtection prot = reserve ? FileMapProtection.SectionReserve : FileMapProtection.SectionCommit; nint handle = WindowsApi.CreateFileMapping( WindowsApi.InvalidHandleValue, diff --git a/src/Ryujinx.Memory/Range/MultiRange.cs b/src/Ryujinx.Memory/Range/MultiRange.cs index 093e21903..51a93063c 100644 --- a/src/Ryujinx.Memory/Range/MultiRange.cs +++ b/src/Ryujinx.Memory/Range/MultiRange.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Memory.Range } else { - var ranges = new List(); + List ranges = new(); foreach (MemoryRange range in _ranges) { diff --git a/src/Ryujinx.Memory/Range/MultiRangeList.cs b/src/Ryujinx.Memory/Range/MultiRangeList.cs index c3c6ae797..3ca26c892 100644 --- a/src/Ryujinx.Memory/Range/MultiRangeList.cs +++ b/src/Ryujinx.Memory/Range/MultiRangeList.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -54,7 +54,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -97,7 +97,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -172,8 +172,8 @@ namespace Ryujinx.Memory.Range private List GetList() { - var items = _items.AsList(); - var result = new List(); + List> items = _items.AsList(); + List result = new(); foreach (RangeNode item in items) { diff --git a/src/Ryujinx.Memory/Tracking/MemoryTracking.cs b/src/Ryujinx.Memory/Tracking/MemoryTracking.cs index b0141f6ff..0160791e8 100644 --- a/src/Ryujinx.Memory/Tracking/MemoryTracking.cs +++ b/src/Ryujinx.Memory/Tracking/MemoryTracking.cs @@ -229,7 +229,7 @@ namespace Ryujinx.Memory.Tracking /// The memory tracking handle public RegionHandle BeginTracking(ulong address, ulong size, int id, RegionFlags flags = RegionFlags.None) { - var (paAddress, paSize) = PageAlign(address, size); + (ulong paAddress, ulong paSize) = PageAlign(address, size); lock (TrackingLock) { @@ -252,7 +252,7 @@ namespace Ryujinx.Memory.Tracking /// The memory tracking handle internal RegionHandle BeginTrackingBitmap(ulong address, ulong size, ConcurrentBitmap bitmap, int bit, int id, RegionFlags flags = RegionFlags.None) { - var (paAddress, paSize) = PageAlign(address, size); + (ulong paAddress, ulong paSize) = PageAlign(address, size); lock (TrackingLock) { diff --git a/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs b/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs index 6fdca69f5..a9b79ab3e 100644 --- a/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs @@ -320,7 +320,7 @@ namespace Ryujinx.Memory.Tracking if (startHandle == lastHandle) { - var handle = _handles[startHandle]; + RegionHandle handle = _handles[startHandle]; if (_sequenceNumberBitmap.Set(startHandle)) { _uncheckedHandles--; @@ -410,7 +410,7 @@ namespace Ryujinx.Memory.Tracking { GC.SuppressFinalize(this); - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { handle.Dispose(); } diff --git a/src/Ryujinx.Memory/Tracking/RegionHandle.cs b/src/Ryujinx.Memory/Tracking/RegionHandle.cs index 4e81a9723..b938c6ea9 100644 --- a/src/Ryujinx.Memory/Tracking/RegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/RegionHandle.cs @@ -199,7 +199,7 @@ namespace Ryujinx.Memory.Tracking _allRegions.AddRange(_regions); _allRegions.AddRange(_guestRegions); - foreach (var region in _allRegions) + foreach (VirtualRegion region in _allRegions) { region.Handles.Add(this); } @@ -217,8 +217,8 @@ namespace Ryujinx.Memory.Tracking { // Assumes the tracking lock is held, so nothing else can signal right now. - var oldBitmap = Bitmap; - var oldBit = DirtyBit; + ConcurrentBitmap oldBitmap = Bitmap; + int oldBit = DirtyBit; bitmap.Set(bit, Dirty); diff --git a/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs b/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs index 8ea687f79..d75b835c5 100644 --- a/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Memory.Tracking public void ForceDirty(ulong address, ulong size) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null && handle.OverlapsWith(address, size)) { @@ -56,7 +56,7 @@ namespace Ryujinx.Memory.Tracking public void RegisterAction(RegionSignal action) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null) { @@ -67,7 +67,7 @@ namespace Ryujinx.Memory.Tracking public void RegisterPreciseAction(PreciseRegionSignal action) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null) { @@ -273,7 +273,7 @@ namespace Ryujinx.Memory.Tracking { GC.SuppressFinalize(this); - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { handle?.Dispose(); } diff --git a/src/Ryujinx.Memory/Tracking/VirtualRegion.cs b/src/Ryujinx.Memory/Tracking/VirtualRegion.cs index 0484af803..e7cf88a3e 100644 --- a/src/Ryujinx.Memory/Tracking/VirtualRegion.cs +++ b/src/Ryujinx.Memory/Tracking/VirtualRegion.cs @@ -90,7 +90,7 @@ namespace Ryujinx.Memory.Tracking MemoryPermission result = MemoryPermission.ReadAndWrite; - foreach (var handle in Handles) + foreach (RegionHandle handle in Handles) { result &= handle.RequiredPermission; if (result == 0) @@ -143,7 +143,7 @@ namespace Ryujinx.Memory.Tracking // The new region inherits all of our parents. newRegion.Handles = new List(Handles); - foreach (var parent in Handles) + foreach (RegionHandle parent in Handles) { parent.AddChild(newRegion); } diff --git a/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs b/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs index 3ed21d010..d416198cd 100644 --- a/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs +++ b/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs @@ -265,7 +265,7 @@ namespace Ryujinx.Memory nuint pa = TranslateVirtualAddressChecked(va); - var target = GetPhysicalAddressSpan(pa, data.Length); + Span target = GetPhysicalAddressSpan(pa, data.Length); bool changed = !data.SequenceEqual(target); diff --git a/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs b/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs index 626f7d027..344a48be6 100644 --- a/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs +++ b/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs @@ -132,7 +132,7 @@ namespace Ryujinx.Memory.WindowsShared /// Memory block that owns the mapping public void MapView(nint sharedMemory, ulong srcOffset, nint location, nint size, MemoryBlock owner) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -159,7 +159,7 @@ namespace Ryujinx.Memory.WindowsShared { SplitForMap((ulong)location, (ulong)size, srcOffset); - var ptr = WindowsApi.MapViewOfFile3( + IntPtr ptr = WindowsApi.MapViewOfFile3( sharedMemory, WindowsApi.CurrentProcessHandle, location, @@ -191,7 +191,7 @@ namespace Ryujinx.Memory.WindowsShared { ulong endAddress = address + size; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; lock (_mappings) { @@ -200,7 +200,7 @@ namespace Ryujinx.Memory.WindowsShared Debug.Assert(count == 1); Debug.Assert(!IsMapped(overlaps[0].Value)); - var overlap = overlaps[0]; + RangeNode overlap = overlaps[0]; ulong overlapStart = overlap.Start; ulong overlapEnd = overlap.End; @@ -261,7 +261,7 @@ namespace Ryujinx.Memory.WindowsShared /// Memory block that owns the mapping public void UnmapView(nint sharedMemory, nint location, nint size, MemoryBlock owner) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -293,7 +293,7 @@ namespace Ryujinx.Memory.WindowsShared ulong unmapSize = (ulong)size; ulong endAddress = startAddress + unmapSize; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; int count; lock (_mappings) @@ -303,7 +303,7 @@ namespace Ryujinx.Memory.WindowsShared for (int index = 0; index < count; index++) { - var overlap = overlaps[index]; + RangeNode overlap = overlaps[index]; if (IsMapped(overlap.Value)) { @@ -323,8 +323,8 @@ namespace Ryujinx.Memory.WindowsShared // This is necessary because Windows does not support partial view unmaps. // That is, you can only fully unmap a view that was previously mapped, you can't just unmap a chunck of it. - ref var partialUnmapState = ref GetPartialUnmapState(); - ref var partialUnmapLock = ref partialUnmapState.PartialUnmapLock; + ref PartialUnmapState partialUnmapState = ref GetPartialUnmapState(); + ref NativeReaderWriterLock partialUnmapLock = ref partialUnmapState.PartialUnmapLock; partialUnmapLock.UpgradeToWriterLock(); try @@ -404,7 +404,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successor) { successor = node.Successor; - var overlap = node; + RangeNode overlap = node; if (!IsMapped(overlap.Value)) { @@ -460,7 +460,7 @@ namespace Ryujinx.Memory.WindowsShared /// True if the reprotection was successful, false otherwise public bool ReprotectView(nint address, nint size, MemoryPermission permission) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -498,7 +498,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var overlap = node; + RangeNode overlap = node; ulong mappedAddress = overlap.Start; ulong mappedSize = overlap.End - overlap.Start; @@ -608,7 +608,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var protection = node; + RangeNode protection = node; ulong protAddress = protection.Start; ulong protEndAddress = protection.End; @@ -670,7 +670,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var protection = node; + RangeNode protection = node; ulong protAddress = protection.Start; ulong protEndAddress = protection.End; @@ -706,7 +706,7 @@ namespace Ryujinx.Memory.WindowsShared private void RestoreRangeProtection(ulong address, ulong size) { ulong endAddress = address + size; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; int count; lock (_protections) @@ -716,7 +716,7 @@ namespace Ryujinx.Memory.WindowsShared for (int index = 0; index < count; index++) { - var protection = overlaps[index]; + RangeNode protection = overlaps[index]; // If protection is R/W we don't need to reprotect as views are initially mapped as R/W. if (protection.Value == MemoryPermission.ReadAndWrite) diff --git a/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs b/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs index 0dbefbad1..1f5eb8aca 100644 --- a/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs +++ b/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs @@ -24,9 +24,9 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentSize ?? Unsafe.SizeOf()); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out _); @@ -44,12 +44,12 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, 3); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act - ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out var copy); + ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out MyUnmanagedStruct copy); // Assert MyUnmanagedStruct.Assert(ClassicAssert.AreEqual, original, read); @@ -65,12 +65,12 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, int.MaxValue); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act - ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out var copy); + ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out MyUnmanagedStruct copy); // Assert MyUnmanagedStruct.Assert(ClassicAssert.AreEqual, original, read); @@ -89,7 +89,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert ClassicAssert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); sequenceReader.Advance(1); @@ -107,7 +107,7 @@ namespace Ryujinx.Tests.Common.Extensions BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(), TestValue); - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new(new ReadOnlySequence(buffer)); // Act sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -126,7 +126,7 @@ namespace Ryujinx.Tests.Common.Extensions BinaryPrimitives.WriteInt32BigEndian(buffer.AsSpan(), TestValue); - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new(new ReadOnlySequence(buffer)); // Act sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -148,7 +148,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert ClassicAssert.Throws(() => { - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new(new ReadOnlySequence(buffer)); sequenceReader.Advance(1); sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -174,7 +174,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert ClassicAssert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); sequenceReader.Advance(1); @@ -201,7 +201,7 @@ namespace Ryujinx.Tests.Common.Extensions ClassicAssert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); sequenceReader.SetConsumed(MyUnmanagedStruct.SizeOf * StructCount + 1); }); @@ -214,9 +214,9 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentLength); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act sequenceReader.ReadUnmanaged(out MyUnmanagedStruct read); @@ -233,7 +233,7 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentLength); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new(sequence); static void SetConsumedAndAssert(scoped ref SequenceReader sequenceReader, long consumed) { @@ -284,7 +284,7 @@ namespace Ryujinx.Tests.Common.Extensions const int BaseInt32Value = 0x1234abcd; const short BaseInt16Value = 0x5678; - var result = new MyUnmanagedStruct + MyUnmanagedStruct result = new() { BehaviourSize = BaseInt32Value ^ rng.Next(), MemoryPoolsSize = BaseInt32Value ^ rng.Next(), @@ -321,7 +321,7 @@ namespace Ryujinx.Tests.Common.Extensions private static IEnumerable EnumerateNewUnmanagedStructs() { - var rng = new Random(0); + Random rng = new(0); while (true) { @@ -332,7 +332,7 @@ namespace Ryujinx.Tests.Common.Extensions private static ReadOnlySequence CreateSegmentedByteSequence(T[] array, int maxSegmentLength) where T : unmanaged { byte[] arrayBytes = MemoryMarshal.AsBytes(array.AsSpan()).ToArray(); - var memory = new Memory(arrayBytes); + Memory memory = new(arrayBytes); int index = 0; BytesReadOnlySequenceSegment first = null, last = null; @@ -340,7 +340,7 @@ namespace Ryujinx.Tests.Common.Extensions while (index < memory.Length) { int nextSegmentLength = Math.Min(maxSegmentLength, memory.Length - index); - var nextSegment = memory.Slice(index, nextSegmentLength); + Memory nextSegment = memory.Slice(index, nextSegmentLength); if (first == null) { diff --git a/src/Ryujinx.Tests/Cpu/CpuTest32.cs b/src/Ryujinx.Tests/Cpu/CpuTest32.cs index 895a786a3..d4c8156d7 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTest32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTest32.cs @@ -295,7 +295,7 @@ namespace Ryujinx.Tests.Cpu FinalRegs = test.FinalRegs, }); - foreach (var (address, value) in test.MemoryDelta) + foreach ((ulong address, ushort value) in test.MemoryDelta) { testMem[address - DataBaseAddress + 0] = (byte)(value >> 0); testMem[address - DataBaseAddress + 1] = (byte)(value >> 8); diff --git a/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs b/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs index 501043a63..f31c7691e 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs @@ -466,7 +466,7 @@ namespace Ryujinx.Tests.Cpu opcode |= (fixImm & 0x3f) << 16; - var v0 = new V128((uint)s0, (uint)s1, (uint)s2, (uint)s3); + V128 v0 = new((uint)s0, (uint)s1, (uint)s2, (uint)s3); SingleOpcode(opcode, v0: v0); @@ -506,7 +506,7 @@ namespace Ryujinx.Tests.Cpu opcode |= (fixImm & 0x3f) << 16; - var v0 = new V128(s0, s1, s2, s3); + V128 v0 = new(s0, s1, s2, s3); SingleOpcode(opcode, v0: v0); diff --git a/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs b/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs index 4b3b5d096..9bc24b300 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs @@ -44,7 +44,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 3u)] uint n, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4a00000u; // VLD1.8 {D0[0]}, [R0], R0 @@ -74,7 +74,7 @@ namespace Ryujinx.Tests.Cpu [Values] bool t, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4a00c00u; // VLD1.8 {D0[0]}, [R0], R0 @@ -103,7 +103,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 10u)] uint mode, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4200000u; // VLD4.8 {D0, D1, D2, D3}, [R0], R0 @@ -133,7 +133,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 3u)] uint n, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); (V128 vec1, V128 vec2, V128 vec3, V128 vec4) = GenerateTestVectors(); @@ -164,7 +164,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 10u)] uint mode, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); (V128 vec1, V128 vec2, V128 vec3, V128 vec4) = GenerateTestVectors(); @@ -194,7 +194,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x1u, 0x32u)] uint regs, [Values] bool single) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xec100a00u; // VST4.8 {D0, D1, D2, D3}, [R0], R0 @@ -246,7 +246,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x0u)] uint imm, [Values] bool sub) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xed900a00u; // VLDR.32 S0, [R0, #0] @@ -281,7 +281,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x0u)] uint imm, [Values] bool sub) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xed800a00u; // VSTR.32 S0, [R0, #0] @@ -331,7 +331,7 @@ namespace Ryujinx.Tests.Cpu data[i] = i + (i / 9f); } - var result = new byte[length]; + byte[] result = new byte[length]; Buffer.BlockCopy(data, 0, result, 0, result.Length); return result; } diff --git a/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs b/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs index 54cc8d52f..7f28d32e5 100644 --- a/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs +++ b/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs @@ -54,7 +54,7 @@ namespace Ryujinx.Tests.Cpu bool methodCalled = false; bool isFz = false; - var method = TranslatorTestMethods.GenerateFpFlagsPInvokeTest(); + TranslatorTestMethods.FpFlagsPInvokeTest method = TranslatorTestMethods.GenerateFpFlagsPInvokeTest(); // This method sets flush-to-zero and then calls the managed method. // Before and after setting the flags, it ensures subnormal addition works as expected. diff --git a/src/Ryujinx.Tests/Memory/PartialUnmaps.cs b/src/Ryujinx.Tests/Memory/PartialUnmaps.cs index 2115be190..f8ab2546c 100644 --- a/src/Ryujinx.Tests/Memory/PartialUnmaps.cs +++ b/src/Ryujinx.Tests/Memory/PartialUnmaps.cs @@ -4,6 +4,7 @@ using ARMeilleure.Signal; using ARMeilleure.Translation; using NUnit.Framework; using NUnit.Framework.Legacy; +using Ryujinx.Common.Memory; using Ryujinx.Common.Memory.PartialUnmaps; using Ryujinx.Cpu; using Ryujinx.Cpu.Jit; @@ -28,11 +29,11 @@ namespace Ryujinx.Tests.Memory { MemoryAllocationFlags asFlags = MemoryAllocationFlags.Reserve | MemoryAllocationFlags.ViewCompatible; - var addressSpace = new MemoryBlock(asSize, asFlags); - var addressSpaceMirror = new MemoryBlock(asSize, asFlags); + MemoryBlock addressSpace = new(asSize, asFlags); + MemoryBlock addressSpaceMirror = new(asSize, asFlags); - var tracking = new MemoryTracking(new MockVirtualMemoryManager(asSize, 0x1000), 0x1000); - var exceptionHandler = new MemoryEhMeilleure(addressSpace, addressSpaceMirror, tracking); + MemoryTracking tracking = new(new MockVirtualMemoryManager(asSize, 0x1000), 0x1000); + MemoryEhMeilleure exceptionHandler = new(addressSpace, addressSpaceMirror, tracking); return (addressSpace, addressSpaceMirror, exceptionHandler); } @@ -41,7 +42,7 @@ namespace Ryujinx.Tests.Memory { int count = 0; - ref var ids = ref state.LocalCounts.ThreadIds; + ref Array20 ids = ref state.LocalCounts.ThreadIds; for (int i = 0; i < ids.Length; i++) { @@ -75,13 +76,13 @@ namespace Ryujinx.Tests.Memory ulong vaSize = 0x100000; // The first 0x100000 is mapped to start. It is replaced from the center with the 0x200000 mapping. - var backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); + MemoryBlock backing = new(vaSize * 2, MemoryAllocationFlags.Mirrorable); (MemoryBlock unusedMainMemory, MemoryBlock memory, MemoryEhMeilleure exceptionHandler) = GetVirtual(vaSize * 2); EnsureTranslator(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); Thread testThread = null; bool shouldAccess = true; @@ -220,17 +221,17 @@ namespace Ryujinx.Tests.Memory ulong vaSize = 0x100000; // The first 0x100000 is mapped to start. It is replaced from the center with the 0x200000 mapping. - var backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); + MemoryBlock backing = new(vaSize * 2, MemoryAllocationFlags.Mirrorable); (MemoryBlock mainMemory, MemoryBlock unusedMirror, MemoryEhMeilleure exceptionHandler) = GetVirtual(vaSize * 2); EnsureTranslator(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); // Create some info to be used for managing the native writing loop. int stateSize = Unsafe.SizeOf(); - var statePtr = Marshal.AllocHGlobal(stateSize); + IntPtr statePtr = Marshal.AllocHGlobal(stateSize); Unsafe.InitBlockUnaligned((void*)statePtr, 0, (uint)stateSize); ref NativeWriteLoopState writeLoopState = ref Unsafe.AsRef((void*)statePtr); @@ -245,7 +246,7 @@ namespace Ryujinx.Tests.Memory // Create a large mapping. mainMemory.MapView(backing, 0, 0, vaSize); - var writeFunc = TestMethods.GenerateDebugNativeWriteLoop(); + TestMethods.DebugNativeWriteLoop writeFunc = TestMethods.GenerateDebugNativeWriteLoop(); nint writePtr = mainMemory.GetPointer(vaSize - 0x1000, 4); Thread testThread = new(() => @@ -296,10 +297,10 @@ namespace Ryujinx.Tests.Memory public void ThreadLocalMap() { PartialUnmapState.Reset(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); bool running = true; - var testThread = new Thread(() => + Thread testThread = new(() => { PartialUnmapState.GetRef().RetryFromAccessViolation(); while (running) @@ -335,11 +336,11 @@ namespace Ryujinx.Tests.Memory PartialUnmapState.Reset(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); fixed (void* localMap = &state.LocalCounts) { - var getOrReserve = TestMethods.GenerateDebugThreadLocalMapGetOrReserve((nint)localMap); + TestMethods.DebugThreadLocalMapGetOrReserve getOrReserve = TestMethods.GenerateDebugThreadLocalMapGetOrReserve((nint)localMap); for (int i = 0; i < ThreadLocalMap.MapSize; i++) { @@ -379,8 +380,8 @@ namespace Ryujinx.Tests.Memory [Test] public void NativeReaderWriterLock() { - var rwLock = new NativeReaderWriterLock(); - var threads = new List(); + NativeReaderWriterLock rwLock = new(); + List threads = new(); int value = 0; @@ -390,7 +391,7 @@ namespace Ryujinx.Tests.Memory for (int i = 0; i < 5; i++) { - var readThread = new Thread(() => + Thread readThread = new(() => { int count = 0; while (running) @@ -427,7 +428,7 @@ namespace Ryujinx.Tests.Memory for (int i = 0; i < 2; i++) { - var writeThread = new Thread(() => + Thread writeThread = new(() => { int count = 0; while (running) @@ -457,7 +458,7 @@ namespace Ryujinx.Tests.Memory threads.Add(writeThread); } - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Start(); } @@ -466,7 +467,7 @@ namespace Ryujinx.Tests.Memory running = false; - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Join(); } diff --git a/src/Ryujinx.UI.Common/App/ApplicationData.cs b/src/Ryujinx.UI.Common/App/ApplicationData.cs index 837d24c30..ab4de916d 100644 --- a/src/Ryujinx.UI.Common/App/ApplicationData.cs +++ b/src/Ryujinx.UI.Common/App/ApplicationData.cs @@ -73,14 +73,14 @@ namespace Ryujinx.UI.App.Common } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; } foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -155,7 +155,7 @@ namespace Ryujinx.UI.App.Common return string.Empty; } - using var nsoFile = new UniqueRef(); + using UniqueRef nsoFile = new(); codeFs.OpenFile(ref nsoFile.Ref, $"/{MainExeFs}".ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.UI.Common/App/ApplicationLibrary.cs b/src/Ryujinx.UI.Common/App/ApplicationLibrary.cs index 728d49ff1..27fa9a6e2 100644 --- a/src/Ryujinx.UI.Common/App/ApplicationLibrary.cs +++ b/src/Ryujinx.UI.Common/App/ApplicationLibrary.cs @@ -209,7 +209,7 @@ namespace Ryujinx.UI.App.Common /// An error occured while reading PFS data. private List GetApplicationsFromPfs(IFileSystem pfs, string filePath) { - var applications = new List(); + List applications = new(); string extension = Path.GetExtension(filePath).ToLower(); foreach ((ulong titleId, ContentMetaData content) in pfs.GetContentData(ContentMetaType.Application, _virtualFileSystem, _checkLevel)) @@ -264,7 +264,7 @@ namespace Ryujinx.UI.App.Common continue; } - using var icon = new UniqueRef(); + using UniqueRef icon = new(); controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -332,7 +332,7 @@ namespace Ryujinx.UI.App.Common case ".nsp": case ".pfs0": { - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new(); pfs.Initialize(file.AsStorage()).ThrowIfFailure(); ApplicationData result = GetApplicationFromNsp(pfs, applicationPath); @@ -457,7 +457,7 @@ namespace Ryujinx.UI.App.Common return false; } - foreach (var data in applications) + foreach (ApplicationData data in applications) { // Only load metadata for applications with an ID if (data.Id != 0) @@ -524,7 +524,7 @@ namespace Ryujinx.UI.App.Common foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -611,8 +611,8 @@ namespace Ryujinx.UI.App.Common nacpFile.Get.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure(); - var displayVersion = controlData.DisplayVersionString.ToString(); - var update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, + string displayVersion = controlData.DisplayVersionString.ToString(); + TitleUpdateModel update = new(content.ApplicationId, content.Version.Version, displayVersion, filePath); titleUpdates.Add(update); @@ -709,11 +709,11 @@ namespace Ryujinx.UI.App.Common return; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; applicationPaths.Add(fullPath); numApplicationsFound++; @@ -743,7 +743,7 @@ namespace Ryujinx.UI.App.Common { _applications.Edit(it => { - foreach (var application in applications) + foreach (ApplicationData application in applications) { it.AddOrUpdate(application); LoadDlcForApplication(application); @@ -802,7 +802,7 @@ namespace Ryujinx.UI.App.Common using HttpClient httpClient = new(); string ldnGameDataArrayString = await httpClient.GetStringAsync($"https://{ldnWebHost}/api/public_games"); IEnumerable ldnGameDataArray = JsonHelper.Deserialize(ldnGameDataArrayString, _ldnDataSerializerContext.IEnumerableLdnGameData); - var evt = new LdnGameDataReceivedEventArgs + LdnGameDataReceivedEventArgs evt = new() { LdnData = ldnGameDataArray }; @@ -865,7 +865,7 @@ namespace Ryujinx.UI.App.Common { // Remove any downloadable content which can no longer be located on disk Logger.Notice.Print(LogClass.Application, $"Removing non-existing Title DLCs"); - var dlcToRemove = _downloadableContents.Items + List<(DownloadableContentModel Dlc, bool IsEnabled)> dlcToRemove = _downloadableContents.Items .Where(dlc => !File.Exists(dlc.Dlc.ContainerPath)) .ToList(); dlcToRemove.ForEach(dlc => @@ -909,11 +909,11 @@ namespace Ryujinx.UI.App.Common return newDlcLoaded; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; dlcPaths.Add(fullPath); } @@ -931,7 +931,7 @@ namespace Ryujinx.UI.App.Common } } - var appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); + HashSet appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); foreach (string dlcPath in dlcPaths) { @@ -940,9 +940,9 @@ namespace Ryujinx.UI.App.Common return newDlcLoaded; } - if (TryGetDownloadableContentFromFile(dlcPath, out var foundDlcs)) + if (TryGetDownloadableContentFromFile(dlcPath, out List foundDlcs)) { - foreach (var dlc in foundDlcs.Where(it => appIdLookup.Contains(it.TitleIdBase))) + foreach (DownloadableContentModel dlc in foundDlcs.Where(it => appIdLookup.Contains(it.TitleIdBase))) { if (!_downloadableContents.Lookup(dlc).HasValue) { @@ -976,12 +976,12 @@ namespace Ryujinx.UI.App.Common try { - var titleIdsToSave = new HashSet(); - var titleIdsToRefresh = new HashSet(); + HashSet titleIdsToSave = new(); + HashSet titleIdsToRefresh = new(); // Remove any updates which can no longer be located on disk Logger.Notice.Print(LogClass.Application, $"Removing non-existing Title Updates"); - var updatesToRemove = _titleUpdates.Items + List<(TitleUpdateModel TitleUpdate, bool IsSelected)> updatesToRemove = _titleUpdates.Items .Where(it => !File.Exists(it.TitleUpdate.Path)) .ToList(); @@ -1028,11 +1028,11 @@ namespace Ryujinx.UI.App.Common return numUpdatesLoaded; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; updatePaths.Add(fullPath); } @@ -1050,7 +1050,7 @@ namespace Ryujinx.UI.App.Common } } - var appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); + HashSet appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); foreach (string updatePath in updatePaths) { @@ -1059,9 +1059,9 @@ namespace Ryujinx.UI.App.Common return numUpdatesLoaded; } - if (TryGetTitleUpdatesFromFile(updatePath, out var foundUpdates)) + if (TryGetTitleUpdatesFromFile(updatePath, out List foundUpdates)) { - foreach (var update in foundUpdates.Where(it => appIdLookup.Contains(it.TitleIdBase))) + foreach (TitleUpdateModel update in foundUpdates.Where(it => appIdLookup.Contains(it.TitleIdBase))) { if (!_titleUpdates.Lookup(update).HasValue) { @@ -1078,8 +1078,8 @@ namespace Ryujinx.UI.App.Common } } - foreach (var titleId in titleIdsToSave) SaveTitleUpdatesForGame(titleId); - foreach (var titleId in titleIdsToRefresh) RefreshApplicationInfo(titleId); + foreach (ulong titleId in titleIdsToSave) SaveTitleUpdatesForGame(titleId); + foreach (ulong titleId in titleIdsToRefresh) RefreshApplicationInfo(titleId); } finally { @@ -1097,8 +1097,8 @@ namespace Ryujinx.UI.App.Common var currentlySelected = TitleUpdates.Items.FirstOrOptional(it => it.TitleUpdate.TitleIdBase == update.TitleIdBase && it.IsSelected); - var shouldSelect = !currentlySelected.HasValue || - currentlySelected.Value.TitleUpdate.Version < update.Version; + bool shouldSelect = !currentlySelected.HasValue || + currentlySelected.Value.TitleUpdate.Version < update.Version; _titleUpdates.AddOrUpdate((update, shouldSelect)); @@ -1207,7 +1207,7 @@ namespace Ryujinx.UI.App.Common } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; @@ -1241,7 +1241,7 @@ namespace Ryujinx.UI.App.Common // Read the icon from the ControlFS and store it as a byte array try { - using var icon = new UniqueRef(); + using UniqueRef icon = new(); controlFs?.OpenFile(ref icon.Ref, $"/icon_{desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -1259,7 +1259,7 @@ namespace Ryujinx.UI.App.Common continue; } - using var icon = new UniqueRef(); + using UniqueRef icon = new(); controlFs?.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -1459,16 +1459,16 @@ namespace Ryujinx.UI.App.Common { _downloadableContents.Edit(it => { - var savedDlc = + List<(DownloadableContentModel, bool IsEnabled)> savedDlc = DownloadableContentsHelper.LoadDownloadableContentsJson(_virtualFileSystem, application.IdBase); it.AddOrUpdate(savedDlc); - if (TryGetDownloadableContentFromFile(application.Path, out var bundledDlc)) + if (TryGetDownloadableContentFromFile(application.Path, out List bundledDlc)) { - var savedDlcLookup = savedDlc.Select(dlc => dlc.Item1).ToHashSet(); + HashSet savedDlcLookup = savedDlc.Select(dlc => dlc.Item1).ToHashSet(); bool addedNewDlc = false; - foreach (var dlc in bundledDlc) + foreach (DownloadableContentModel dlc in bundledDlc) { if (!savedDlcLookup.Contains(dlc)) { @@ -1491,22 +1491,22 @@ namespace Ryujinx.UI.App.Common // file itself private bool LoadTitleUpdatesForApplication(ApplicationData application) { - var modifiedVersion = false; + bool modifiedVersion = false; _titleUpdates.Edit(it => { - var savedUpdates = + List<(TitleUpdateModel Update, bool IsSelected)> savedUpdates = TitleUpdatesHelper.LoadTitleUpdatesJson(_virtualFileSystem, application.IdBase); it.AddOrUpdate(savedUpdates); var selectedUpdate = savedUpdates.FirstOrOptional(update => update.IsSelected); - if (TryGetTitleUpdatesFromFile(application.Path, out var bundledUpdates)) + if (TryGetTitleUpdatesFromFile(application.Path, out List bundledUpdates)) { - var savedUpdateLookup = savedUpdates.Select(update => update.Update).ToHashSet(); + HashSet savedUpdateLookup = savedUpdates.Select(update => update.Update).ToHashSet(); bool updatesChanged = false; - foreach (var update in bundledUpdates.OrderByDescending(bundled => bundled.Version)) + foreach (TitleUpdateModel update in bundledUpdates.OrderByDescending(bundled => bundled.Version)) { if (!savedUpdateLookup.Contains(update)) { @@ -1540,14 +1540,14 @@ namespace Ryujinx.UI.App.Common // Save the _currently tracked_ DLC state for the game private void SaveDownloadableContentsForGame(ulong titleIdBase) { - var dlcs = DownloadableContents.Items.Where(dlc => dlc.Dlc.TitleIdBase == titleIdBase).ToList(); + List<(DownloadableContentModel Dlc, bool IsEnabled)> dlcs = DownloadableContents.Items.Where(dlc => dlc.Dlc.TitleIdBase == titleIdBase).ToList(); DownloadableContentsHelper.SaveDownloadableContentsJson(_virtualFileSystem, titleIdBase, dlcs); } // Save the _currently tracked_ update state for the game private void SaveTitleUpdatesForGame(ulong titleIdBase) { - var updates = TitleUpdates.Items.Where(update => update.TitleUpdate.TitleIdBase == titleIdBase).ToList(); + List<(TitleUpdateModel TitleUpdate, bool IsSelected)> updates = TitleUpdates.Items.Where(update => update.TitleUpdate.TitleIdBase == titleIdBase).ToList(); TitleUpdatesHelper.SaveTitleUpdatesJson(_virtualFileSystem, titleIdBase, updates); } @@ -1555,7 +1555,7 @@ namespace Ryujinx.UI.App.Common // of its state private void RefreshApplicationInfo(ulong appIdBase) { - var application = _applications.Lookup(appIdBase); + Optional application = _applications.Lookup(appIdBase); if (!application.HasValue) return; @@ -1563,7 +1563,7 @@ namespace Ryujinx.UI.App.Common if (!TryGetApplicationsFromFile(application.Value.Path, out List newApplications)) return; - var newApplication = newApplications.First(it => it.IdBase == appIdBase); + ApplicationData newApplication = newApplications.First(it => it.IdBase == appIdBase); _applications.AddOrUpdate(newApplication); } } diff --git a/src/Ryujinx.UI.Common/Configuration/ConfigurationState.cs b/src/Ryujinx.UI.Common/Configuration/ConfigurationState.cs index 44ba90ace..16da0ea3d 100644 --- a/src/Ryujinx.UI.Common/Configuration/ConfigurationState.cs +++ b/src/Ryujinx.UI.Common/Configuration/ConfigurationState.cs @@ -1787,7 +1787,7 @@ namespace Ryujinx.UI.Common.Configuration bool didPathUpdate = false; { // Game dirs - foreach (var gameDir in UI.GameDirs.Value) + foreach (string gameDir in UI.GameDirs.Value) { if (Directory.Exists(gameDir)) { @@ -1806,7 +1806,7 @@ namespace Ryujinx.UI.Common.Configuration existingDirs.Clear(); { // Autoload dirs - foreach (var autoloadDir in UI.AutoloadDirs.Value) + foreach (string autoloadDir in UI.AutoloadDirs.Value) { if (Directory.Exists(autoloadDir)) { diff --git a/src/Ryujinx.UI.Common/Configuration/LoggerModule.cs b/src/Ryujinx.UI.Common/Configuration/LoggerModule.cs index 9cb283593..61928b183 100644 --- a/src/Ryujinx.UI.Common/Configuration/LoggerModule.cs +++ b/src/Ryujinx.UI.Common/Configuration/LoggerModule.cs @@ -67,12 +67,12 @@ namespace Ryujinx.UI.Common.Configuration { bool noFilter = e.NewValue.Length == 0; - foreach (var logClass in Enum.GetValues()) + foreach (LogClass logClass in Enum.GetValues()) { Logger.SetEnable(logClass, noFilter); } - foreach (var logClass in e.NewValue) + foreach (LogClass logClass in e.NewValue) { Logger.SetEnable(logClass, true); } diff --git a/src/Ryujinx.UI.Common/Helper/DownloadableContentsHelper.cs b/src/Ryujinx.UI.Common/Helper/DownloadableContentsHelper.cs index f7a109379..8d4fd5492 100644 --- a/src/Ryujinx.UI.Common/Helper/DownloadableContentsHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/DownloadableContentsHelper.cs @@ -22,7 +22,7 @@ namespace Ryujinx.UI.Common.Helper public static List<(DownloadableContentModel, bool IsEnabled)> LoadDownloadableContentsJson(VirtualFileSystem vfs, ulong applicationIdBase) { - var downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); + string downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); if (!File.Exists(downloadableContentJsonPath)) { @@ -31,7 +31,7 @@ namespace Ryujinx.UI.Common.Helper try { - var downloadableContentContainerList = JsonHelper.DeserializeFromFile(downloadableContentJsonPath, + List downloadableContentContainerList = JsonHelper.DeserializeFromFile(downloadableContentJsonPath, _serializerContext.ListDownloadableContentContainer); return LoadDownloadableContents(vfs, downloadableContentContainerList); } @@ -76,13 +76,13 @@ namespace Ryujinx.UI.Common.Helper downloadableContentContainerList.Add(container); } - var downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); + string downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); JsonHelper.SerializeToFile(downloadableContentJsonPath, downloadableContentContainerList, _serializerContext.ListDownloadableContentContainer); } private static List<(DownloadableContentModel, bool IsEnabled)> LoadDownloadableContents(VirtualFileSystem vfs, List downloadableContentContainers) { - var result = new List<(DownloadableContentModel, bool IsEnabled)>(); + List<(DownloadableContentModel, bool IsEnabled)> result = new(); foreach (DownloadableContentContainer downloadableContentContainer in downloadableContentContainers) { @@ -105,7 +105,7 @@ namespace Ryujinx.UI.Common.Helper continue; } - var content = new DownloadableContentModel(nca.Header.TitleId, + DownloadableContentModel content = new(nca.Header.TitleId, downloadableContentContainer.ContainerPath, downloadableContentNca.FullPath); diff --git a/src/Ryujinx.UI.Common/Helper/FileAssociationHelper.cs b/src/Ryujinx.UI.Common/Helper/FileAssociationHelper.cs index d1e67325f..efd3a3efc 100644 --- a/src/Ryujinx.UI.Common/Helper/FileAssociationHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/FileAssociationHelper.cs @@ -101,7 +101,7 @@ namespace Ryujinx.UI.Common.Helper { RegistryKey key = Registry.CurrentUser.OpenSubKey(@$"Software\Classes\{ext}"); - var openCmd = key?.OpenSubKey(@"shell\open\command"); + RegistryKey openCmd = key?.OpenSubKey(@"shell\open\command"); if (openCmd is null) { @@ -143,7 +143,7 @@ namespace Ryujinx.UI.Common.Helper } else { - using var key = Registry.CurrentUser.CreateSubKey(keyString); + using RegistryKey key = Registry.CurrentUser.CreateSubKey(keyString); if (key is null) { @@ -151,7 +151,7 @@ namespace Ryujinx.UI.Common.Helper } Logger.Debug?.Print(LogClass.Application, $"Adding type association {ext}"); - using var openCmd = key.CreateSubKey(@"shell\open\command"); + using RegistryKey openCmd = key.CreateSubKey(@"shell\open\command"); openCmd?.SetValue("", $"\"{Environment.ProcessPath}\" \"%1\""); Logger.Debug?.Print(LogClass.Application, $"Added type association {ext}"); diff --git a/src/Ryujinx.UI.Common/Helper/LinuxHelper.cs b/src/Ryujinx.UI.Common/Helper/LinuxHelper.cs index b57793791..beacdcf5a 100644 --- a/src/Ryujinx.UI.Common/Helper/LinuxHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/LinuxHelper.cs @@ -24,7 +24,7 @@ namespace Ryujinx.UI.Common.Helper return null; } - foreach (var searchPath in pathVar.Split(":", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (string searchPath in pathVar.Split(":", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { string binaryPath = Path.Combine(searchPath, binary); diff --git a/src/Ryujinx.UI.Common/Helper/OpenHelper.cs b/src/Ryujinx.UI.Common/Helper/OpenHelper.cs index 8b0e1f1fd..8f1a5d201 100644 --- a/src/Ryujinx.UI.Common/Helper/OpenHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/OpenHelper.cs @@ -57,7 +57,7 @@ namespace Ryujinx.UI.Common.Helper { ObjectiveC.NSString nsStringPath = new(path); ObjectiveC.Object nsUrl = new("NSURL"); - var urlPtr = nsUrl.GetFromMessage("fileURLWithPath:", nsStringPath); + ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("fileURLWithPath:", nsStringPath); ObjectiveC.Object nsArray = new("NSArray"); ObjectiveC.Object urlArray = nsArray.GetFromMessage("arrayWithObject:", urlPtr); @@ -96,7 +96,7 @@ namespace Ryujinx.UI.Common.Helper { ObjectiveC.NSString nsStringPath = new(url); ObjectiveC.Object nsUrl = new("NSURL"); - var urlPtr = nsUrl.GetFromMessage("URLWithString:", nsStringPath); + ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("URLWithString:", nsStringPath); ObjectiveC.Object nsWorkspace = new("NSWorkspace"); ObjectiveC.Object sharedWorkspace = nsWorkspace.GetFromMessage("sharedWorkspace"); diff --git a/src/Ryujinx.UI.Common/Helper/ShortcutHelper.cs b/src/Ryujinx.UI.Common/Helper/ShortcutHelper.cs index d437c1753..e154f40c8 100644 --- a/src/Ryujinx.UI.Common/Helper/ShortcutHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/ShortcutHelper.cs @@ -18,11 +18,11 @@ namespace Ryujinx.UI.Common.Helper iconPath += ".ico"; MemoryStream iconDataStream = new(iconData); - using var image = SKBitmap.Decode(iconDataStream); + using SKBitmap image = SKBitmap.Decode(iconDataStream); image.Resize(new SKImageInfo(128, 128), SKFilterQuality.High); SaveBitmapAsIcon(image, iconPath); - var shortcut = Shortcut.CreateShortcut(basePath, GetArgsString(applicationFilePath, applicationId), iconPath, 0); + Shortcut shortcut = Shortcut.CreateShortcut(basePath, GetArgsString(applicationFilePath, applicationId), iconPath, 0); shortcut.StringData.NameString = cleanedAppName; shortcut.WriteToFile(Path.Combine(desktopPath, cleanedAppName + ".lnk")); } @@ -31,12 +31,12 @@ namespace Ryujinx.UI.Common.Helper private static void CreateShortcutLinux(string applicationFilePath, string applicationId, byte[] iconData, string iconPath, string desktopPath, string cleanedAppName) { string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx.sh"); - var desktopFile = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-template.desktop"); + string desktopFile = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-template.desktop"); iconPath += ".png"; - var image = SKBitmap.Decode(iconData); + SKBitmap image = SKBitmap.Decode(iconData); using var data = image.Encode(SKEncodedImageFormat.Png, 100); - using var file = File.OpenWrite(iconPath); + using FileStream file = File.OpenWrite(iconPath); data.SaveTo(file); using StreamWriter outputFile = new(Path.Combine(desktopPath, cleanedAppName + ".desktop")); @@ -47,8 +47,8 @@ namespace Ryujinx.UI.Common.Helper private static void CreateShortcutMacos(string appFilePath, string applicationId, byte[] iconData, string desktopPath, string cleanedAppName) { string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"); - var plistFile = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-template.plist"); - var shortcutScript = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-launch-script.sh"); + string plistFile = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-template.plist"); + string shortcutScript = EmbeddedResources.ReadAllText("Ryujinx.UI.Common/shortcut-launch-script.sh"); // Macos .App folder string contentFolderPath = Path.Combine("/Applications", cleanedAppName + ".app", "Contents"); string scriptFolderPath = Path.Combine(contentFolderPath, "MacOS"); @@ -77,9 +77,9 @@ namespace Ryujinx.UI.Common.Helper } const string IconName = "icon.png"; - var image = SKBitmap.Decode(iconData); + SKBitmap image = SKBitmap.Decode(iconData); using var data = image.Encode(SKEncodedImageFormat.Png, 100); - using var file = File.OpenWrite(Path.Combine(resourceFolderPath, IconName)); + using FileStream file = File.OpenWrite(Path.Combine(resourceFolderPath, IconName)); data.SaveTo(file); // plist file @@ -124,7 +124,7 @@ namespace Ryujinx.UI.Common.Helper private static string GetArgsString(string appFilePath, string applicationId) { // args are first defined as a list, for easier adjustments in the future - var argsList = new List(); + List argsList = new(); if (!string.IsNullOrEmpty(CommandLineState.BaseDirPathArg)) { diff --git a/src/Ryujinx.UI.Common/Helper/TitleUpdatesHelper.cs b/src/Ryujinx.UI.Common/Helper/TitleUpdatesHelper.cs index 975eda3ff..a54542427 100644 --- a/src/Ryujinx.UI.Common/Helper/TitleUpdatesHelper.cs +++ b/src/Ryujinx.UI.Common/Helper/TitleUpdatesHelper.cs @@ -30,7 +30,7 @@ namespace Ryujinx.UI.Common.Helper public static List<(TitleUpdateModel Update, bool IsSelected)> LoadTitleUpdatesJson(VirtualFileSystem vfs, ulong applicationIdBase) { - var titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); + string titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); if (!File.Exists(titleUpdatesJsonPath)) { @@ -39,7 +39,7 @@ namespace Ryujinx.UI.Common.Helper try { - var titleUpdateWindowData = JsonHelper.DeserializeFromFile(titleUpdatesJsonPath, _serializerContext.TitleUpdateMetadata); + TitleUpdateMetadata titleUpdateWindowData = JsonHelper.DeserializeFromFile(titleUpdatesJsonPath, _serializerContext.TitleUpdateMetadata); return LoadTitleUpdates(vfs, titleUpdateWindowData, applicationIdBase); } catch @@ -51,7 +51,7 @@ namespace Ryujinx.UI.Common.Helper public static void SaveTitleUpdatesJson(VirtualFileSystem vfs, ulong applicationIdBase, List<(TitleUpdateModel, bool IsSelected)> updates) { - var titleUpdateWindowData = new TitleUpdateMetadata + TitleUpdateMetadata titleUpdateWindowData = new() { Selected = "", Paths = [], @@ -73,13 +73,13 @@ namespace Ryujinx.UI.Common.Helper } } - var titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); + string titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); JsonHelper.SerializeToFile(titleUpdatesJsonPath, titleUpdateWindowData, _serializerContext.TitleUpdateMetadata); } private static List<(TitleUpdateModel Update, bool IsSelected)> LoadTitleUpdates(VirtualFileSystem vfs, TitleUpdateMetadata titleUpdateMetadata, ulong applicationIdBase) { - var result = new List<(TitleUpdateModel, bool IsSelected)>(); + List<(TitleUpdateModel, bool IsSelected)> result = new(); IntegrityCheckLevel checkLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid @@ -121,8 +121,8 @@ namespace Ryujinx.UI.Common.Helper nacpFile.Get.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None) .ThrowIfFailure(); - var displayVersion = controlData.DisplayVersionString.ToString(); - var update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, + string displayVersion = controlData.DisplayVersionString.ToString(); + TitleUpdateModel update = new(content.ApplicationId, content.Version.Version, displayVersion, path); result.Add((update, path == titleUpdateMetadata.Selected)); diff --git a/src/Ryujinx.UI.Common/Helper/ValueFormatUtils.cs b/src/Ryujinx.UI.Common/Helper/ValueFormatUtils.cs index 7bd812c3b..f0202cd49 100644 --- a/src/Ryujinx.UI.Common/Helper/ValueFormatUtils.cs +++ b/src/Ryujinx.UI.Common/Helper/ValueFormatUtils.cs @@ -140,10 +140,10 @@ namespace Ryujinx.UI.Common.Helper // An input string can either look like "01:23:45" or "1d, 01:23:45" if the timespan represents a duration of more than a day. // Here, we split the input string to check if it's the former or the latter. - var valueSplit = timeSpanString.Split(", "); + string[] valueSplit = timeSpanString.Split(", "); if (valueSplit.Length > 1) { - var dayPart = valueSplit[0].Split("d")[0]; + string dayPart = valueSplit[0].Split("d")[0]; if (int.TryParse(dayPart, out int days)) { returnTimeSpan = returnTimeSpan.Add(TimeSpan.FromDays(days)); diff --git a/src/Ryujinx.UI.Common/Models/XCITrimmerFileModel.cs b/src/Ryujinx.UI.Common/Models/XCITrimmerFileModel.cs index 05fa82920..a08f82fb6 100644 --- a/src/Ryujinx.UI.Common/Models/XCITrimmerFileModel.cs +++ b/src/Ryujinx.UI.Common/Models/XCITrimmerFileModel.cs @@ -16,7 +16,7 @@ namespace Ryujinx.UI.Common.Models { public static XCITrimmerFileModel FromApplicationData(ApplicationData applicationData, XCIFileTrimmerLog logger) { - var trimmer = new XCIFileTrimmer(applicationData.Path, logger); + XCIFileTrimmer trimmer = new(applicationData.Path, logger); return new XCITrimmerFileModel( applicationData.Name, diff --git a/src/Ryujinx.UI.Common/SystemInfo/LinuxSystemInfo.cs b/src/Ryujinx.UI.Common/SystemInfo/LinuxSystemInfo.cs index c7fe05a09..f235b17e4 100644 --- a/src/Ryujinx.UI.Common/SystemInfo/LinuxSystemInfo.cs +++ b/src/Ryujinx.UI.Common/SystemInfo/LinuxSystemInfo.cs @@ -16,7 +16,7 @@ namespace Ryujinx.UI.Common.SystemInfo if (cpuName == null) { - var cpuDict = new Dictionary(StringComparer.Ordinal) + Dictionary cpuDict = new(StringComparer.Ordinal) { ["model name"] = null, ["Processor"] = null, @@ -28,7 +28,7 @@ namespace Ryujinx.UI.Common.SystemInfo cpuName = cpuDict["model name"] ?? cpuDict["Processor"] ?? cpuDict["Hardware"] ?? "Unknown"; } - var memDict = new Dictionary(StringComparer.Ordinal) + Dictionary memDict = new(StringComparer.Ordinal) { ["MemTotal"] = null, ["MemAvailable"] = null, diff --git a/src/Ryujinx.UI.Common/SystemInfo/MacOSSystemInfo.cs b/src/Ryujinx.UI.Common/SystemInfo/MacOSSystemInfo.cs index 894c3cadc..886260b0b 100644 --- a/src/Ryujinx.UI.Common/SystemInfo/MacOSSystemInfo.cs +++ b/src/Ryujinx.UI.Common/SystemInfo/MacOSSystemInfo.cs @@ -40,10 +40,10 @@ namespace Ryujinx.UI.Common.SystemInfo static ulong GetVMInfoAvailableMemory() { - var port = mach_host_self(); + uint port = mach_host_self(); uint pageSize = 0; - var result = host_page_size(port, ref pageSize); + int result = host_page_size(port, ref pageSize); if (result != 0) { diff --git a/src/Ryujinx.UI.Common/SystemInfo/WindowsSystemInfo.cs b/src/Ryujinx.UI.Common/SystemInfo/WindowsSystemInfo.cs index 40130adba..a11c2ce22 100644 --- a/src/Ryujinx.UI.Common/SystemInfo/WindowsSystemInfo.cs +++ b/src/Ryujinx.UI.Common/SystemInfo/WindowsSystemInfo.cs @@ -34,7 +34,7 @@ namespace Ryujinx.UI.Common.SystemInfo if (cpuObjs != null) { - foreach (var cpuObj in cpuObjs) + foreach (ManagementBaseObject cpuObj in cpuObjs) { return cpuObj["Name"].ToString()?.Trim(); } diff --git a/src/Ryujinx/App.axaml.cs b/src/Ryujinx/App.axaml.cs index d1ce2a3d2..2ce3e571a 100644 --- a/src/Ryujinx/App.axaml.cs +++ b/src/Ryujinx/App.axaml.cs @@ -77,7 +77,7 @@ namespace Ryujinx.Ava { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogThemeRestartMessage], LocaleManager.Instance[LocaleKeys.DialogThemeRestartSubMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -86,8 +86,8 @@ namespace Ryujinx.Ava if (result == UserResult.Yes) { - var path = Environment.ProcessPath; - var proc = Process.Start(path ?? string.Empty, CommandLineState.Arguments); + string path = Environment.ProcessPath; + Process proc = Process.Start(path ?? string.Empty, CommandLineState.Arguments); desktop.Shutdown(); Environment.Exit(0); } diff --git a/src/Ryujinx/AppHost.cs b/src/Ryujinx/AppHost.cs index 5992509d7..909cd20aa 100644 --- a/src/Ryujinx/AppHost.cs +++ b/src/Ryujinx/AppHost.cs @@ -235,8 +235,8 @@ namespace Ryujinx.Ava var point = e.GetCurrentPoint(window).Position; var bounds = RendererHost.EmbeddedWindow.Bounds; - var windowYOffset = bounds.Y + window.MenuBarHeight; - var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; + double windowYOffset = bounds.Y + window.MenuBarHeight; + double windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; if (!_viewModel.ShowMenuAndStatusBar) { @@ -262,8 +262,8 @@ namespace Ryujinx.Ava { var point = e.GetCurrentPoint(window).Position; var bounds = RendererHost.EmbeddedWindow.Bounds; - var windowYOffset = bounds.Y + window.MenuBarHeight; - var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; + double windowYOffset = bounds.Y + window.MenuBarHeight; + double windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; if (!_viewModel.ShowMenuAndStatusBar) { @@ -462,7 +462,7 @@ namespace Ryujinx.Ava private void SaveBitmapAsPng(SKBitmap bitmap, string path) { using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100); - using var stream = File.OpenWrite(path); + using FileStream stream = File.OpenWrite(path); data.SaveTo(stream); } @@ -922,7 +922,7 @@ namespace Ryujinx.Ava BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading; - var isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); + bool isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); if (isGALThreaded) { renderer = new ThreadedRenderer(renderer); @@ -931,7 +931,7 @@ namespace Ryujinx.Ava Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALThreaded}"); // Initialize Configuration. - var memoryConfiguration = ConfigurationState.Instance.System.DramSize.Value; + MemoryConfiguration memoryConfiguration = ConfigurationState.Instance.System.DramSize.Value; HLEConfiguration configuration = new(VirtualFileSystem, _viewModel.LibHacHorizonManager, @@ -971,7 +971,7 @@ namespace Ryujinx.Ava private static IHardwareDeviceDriver InitializeAudio() { - var availableBackends = new List + List availableBackends = new() { AudioBackend.SDL3, AudioBackend.SoundIo, diff --git a/src/Ryujinx/Common/ApplicationHelper.cs b/src/Ryujinx/Common/ApplicationHelper.cs index 5fabc587e..3d17ced0b 100644 --- a/src/Ryujinx/Common/ApplicationHelper.cs +++ b/src/Ryujinx/Common/ApplicationHelper.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Ava.Common public static void CreateSaveDir(ulong titleId, BlitStruct nacpData) { - var applicationId = new LibHac.Ncm.ApplicationId(titleId); + ApplicationId applicationId = new(titleId); Logger.Info?.Print(LogClass.Application, $"Ensuring required savedata exists for title id: {titleId}."); @@ -174,7 +174,7 @@ namespace Ryujinx.Ava.Common public static void ExtractSection(string destination, NcaSectionType ncaSectionType, string titleFilePath, string titleName, int programIndex = 0) { - var cancellationToken = new CancellationTokenSource(); + CancellationTokenSource cancellationToken = new(); UpdateWaitWindow waitingDialog = new( LocaleManager.Instance[LocaleKeys.DialogNcaExtractionTitle], @@ -201,14 +201,14 @@ namespace Ryujinx.Ava.Common } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; } foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -274,8 +274,8 @@ namespace Ryujinx.Ava.Common string source = DateTime.Now.ToFileTime().ToString()[10..]; string output = DateTime.Now.ToFileTime().ToString()[10..]; - using var uniqueSourceFs = new UniqueRef(ncaFileSystem); - using var uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); + using UniqueRef uniqueSourceFs = new(ncaFileSystem); + using UniqueRef uniqueOutputFs = new(new LocalFileSystem(destination)); fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); @@ -330,7 +330,7 @@ namespace Ryujinx.Ava.Common public static void ExtractAoc(string destination, NcaSectionType ncaSectionType, string updateFilePath, string updateName) { - var cancellationToken = new CancellationTokenSource(); + CancellationTokenSource cancellationToken = new(); UpdateWaitWindow waitingDialog = new( $"Ryujinx {Program.Version} - {LocaleManager.Instance[LocaleKeys.DialogNcaExtractionTitle]}", @@ -348,13 +348,13 @@ namespace Ryujinx.Ava.Common string extension = Path.GetExtension(updateFilePath).ToLower(); if (extension is ".nsp") { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); IFileSystem pfs = pfsTemp; foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -395,8 +395,8 @@ namespace Ryujinx.Ava.Common string source = DateTime.Now.ToFileTime().ToString()[10..]; string output = DateTime.Now.ToFileTime().ToString()[10..]; - using var uniqueSourceFs = new UniqueRef(ncaFileSystem); - using var uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); + using UniqueRef uniqueSourceFs = new(ncaFileSystem); + using UniqueRef uniqueOutputFs = new(new LocalFileSystem(destination)); fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); diff --git a/src/Ryujinx/Common/Locale/LocaleManager.cs b/src/Ryujinx/Common/Locale/LocaleManager.cs index 96f648761..60b16074c 100644 --- a/src/Ryujinx/Common/Locale/LocaleManager.cs +++ b/src/Ryujinx/Common/Locale/LocaleManager.cs @@ -32,7 +32,7 @@ namespace Ryujinx.Ava.Common.Locale private void Load() { - var localeLanguageCode = !string.IsNullOrEmpty(ConfigurationState.Instance.UI.LanguageCode.Value) ? + string localeLanguageCode = !string.IsNullOrEmpty(ConfigurationState.Instance.UI.LanguageCode.Value) ? ConfigurationState.Instance.UI.LanguageCode.Value : CultureInfo.CurrentCulture.Name.Replace('-', '_'); // Load en_US as default, if the target language translation is missing or incomplete. @@ -56,7 +56,7 @@ namespace Ryujinx.Ava.Common.Locale if (_localeStrings.TryGetValue(key, out string value)) { // Check if the localized string needs to be formatted. - if (_dynamicValues.TryGetValue(key, out var dynamicValue)) + if (_dynamicValues.TryGetValue(key, out object[] dynamicValue)) { try { @@ -158,9 +158,9 @@ namespace Ryujinx.Ava.Common.Locale return null; } - var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); + Dictionary strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); - foreach (var item in strings) + foreach (KeyValuePair item in strings) { if (Enum.TryParse(item.Key, out var key)) { diff --git a/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs b/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs index 30e9cea72..d8461fdae 100644 --- a/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs +++ b/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs @@ -292,9 +292,9 @@ namespace Ryujinx.Headless if (!string.IsNullOrEmpty(options.PreferredGPUVendor)) { string preferredGpuVendor = options.PreferredGPUVendor.ToLowerInvariant(); - var devices = VulkanRenderer.GetPhysicalDevices(api); + DeviceInfo[] devices = VulkanRenderer.GetPhysicalDevices(api); - foreach (var device in devices) + foreach (DeviceInfo device in devices) { if (device.Vendor.ToLowerInvariant() == preferredGpuVendor) { diff --git a/src/Ryujinx/Headless/WindowBase.cs b/src/Ryujinx/Headless/WindowBase.cs index 82dd3d61c..e3bc1d185 100644 --- a/src/Ryujinx/Headless/WindowBase.cs +++ b/src/Ryujinx/Headless/WindowBase.cs @@ -1,3 +1,4 @@ +using LibHac.Ns; using LibHac.Util; using Ryujinx.Ava; using Ryujinx.Common; @@ -10,6 +11,7 @@ using Ryujinx.Graphics.Gpu; using Ryujinx.Graphics.OpenGL; using Ryujinx.HLE.HOS.Applets; using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types; +using Ryujinx.HLE.Loaders.Processes; using Ryujinx.HLE.UI; using Ryujinx.Input; using Ryujinx.Input.HLE; @@ -158,8 +160,8 @@ namespace Ryujinx.Headless private void InitializeWindow() { - var activeProcess = Device.Processes.ActiveApplication; - var nacp = activeProcess.ApplicationControlProperties; + ProcessResult activeProcess = Device.Processes.ActiveApplication; + ApplicationControlProperty nacp = activeProcess.ApplicationControlProperties; int desiredLanguage = (int)Device.System.State.DesiredTitleLanguage; string titleNameSection = string.IsNullOrWhiteSpace(nacp.Title[desiredLanguage].NameString.ToString()) ? string.Empty : $" - {nacp.Title[desiredLanguage].NameString.ToString()}"; diff --git a/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs b/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs index 141d1659b..d7cb9542a 100644 --- a/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs +++ b/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs @@ -89,7 +89,7 @@ namespace Ryujinx.Ava.Input return false; } - AvaloniaKeyboardMappingHelper.TryGetAvaKey(key, out var nativeKey); + AvaloniaKeyboardMappingHelper.TryGetAvaKey(key, out AvaKey nativeKey); return _pressedKeys.Contains(nativeKey); } diff --git a/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs b/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs index 1a99bcea8..48e49a7fa 100644 --- a/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs +++ b/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs @@ -151,14 +151,14 @@ namespace Ryujinx.Ava.Input static AvaloniaKeyboardMappingHelper() { - var inputKeys = Enum.GetValues(); + Key[] inputKeys = Enum.GetValues(); // NOTE: Avalonia.Input.Key is not contiguous and quite large, so use a dictionary instead of an array. _avaKeyMapping = new Dictionary(); - foreach (var key in inputKeys) + foreach (Key key in inputKeys) { - if (TryGetAvaKey(key, out var index)) + if (TryGetAvaKey(key, out AvaKey index)) { _avaKeyMapping[index] = key; } diff --git a/src/Ryujinx/Modules/Updater/Updater.cs b/src/Ryujinx/Modules/Updater/Updater.cs index ff9154eed..80990bca2 100644 --- a/src/Ryujinx/Modules/Updater/Updater.cs +++ b/src/Ryujinx/Modules/Updater/Updater.cs @@ -68,7 +68,7 @@ namespace Ryujinx.Modules } else if (OperatingSystem.IsLinux()) { - var arch = RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64"; + string arch = RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64"; _platformExt = $"linux_{arch}.tar.gz"; } @@ -99,10 +99,10 @@ namespace Ryujinx.Modules string buildInfoUrl = $"{GitHubApiUrl}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest"; string fetchedJson = await jsonClient.GetStringAsync(buildInfoUrl); - var fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); + GithubReleasesJsonResponse fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); _buildVer = fetched.Name; - foreach (var asset in fetched.Assets) + foreach (GithubReleaseAssetJsonResponse asset in fetched.Assets) { if (asset.Name.StartsWith("ryujinx") && asset.Name.EndsWith(_platformExt)) { @@ -208,7 +208,7 @@ namespace Ryujinx.Modules await Dispatcher.UIThread.InvokeAsync(async () => { // Show a message asking the user if they want to update - var shouldUpdate = await ContentDialogHelper.CreateChoiceDialog( + bool shouldUpdate = await ContentDialogHelper.CreateChoiceDialog( LocaleManager.Instance[LocaleKeys.RyujinxUpdater], LocaleManager.Instance[LocaleKeys.RyujinxUpdaterMessage], $"{Program.Version} -> {newVersion}"); @@ -716,15 +716,15 @@ namespace Ryujinx.Modules // NOTE: This method should always reflect the latest build layout. private static IEnumerable EnumerateFilesToDelete() { - var files = Directory.EnumerateFiles(_homeDir); // All files directly in base dir. + IEnumerable files = Directory.EnumerateFiles(_homeDir); // All files directly in base dir. // Determine and exclude user files only when the updater is running, not when cleaning old files if (_running && !OperatingSystem.IsMacOS()) { // Compare the loose files in base directory against the loose files from the incoming update, and store foreign ones in a user list. - var oldFiles = Directory.EnumerateFiles(_homeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var newFiles = Directory.EnumerateFiles(_updatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(_homeDir, filename)); + IEnumerable oldFiles = Directory.EnumerateFiles(_homeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + IEnumerable newFiles = Directory.EnumerateFiles(_updatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + IEnumerable userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(_homeDir, filename)); // Remove user files from the paths in files. files = files.Except(userFiles); diff --git a/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs b/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs index efcb7888b..cb347f59b 100644 --- a/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs +++ b/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs @@ -44,7 +44,7 @@ namespace Ryujinx.Ava.UI.Applet Dispatcher.UIThread.InvokeAsync(async () => { - var response = await ControllerAppletDialog.ShowControllerAppletDialog(_parent, args); + UserResult response = await ControllerAppletDialog.ShowControllerAppletDialog(_parent, args); if (response == UserResult.Ok) { okPressed = true; @@ -132,7 +132,7 @@ namespace Ryujinx.Ava.UI.Applet try { _parent.ViewModel.AppHost.NpadManager.BlockInputUpdates(); - var response = await SwkbdAppletDialog.ShowInputDialog(LocaleManager.Instance[LocaleKeys.SoftwareKeyboard], args); + (UserResult Result, string Input) response = await SwkbdAppletDialog.ShowInputDialog(LocaleManager.Instance[LocaleKeys.SoftwareKeyboard], args); if (response.Result == UserResult.Ok) { diff --git a/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs b/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs index 5b5a96423..56413b449 100644 --- a/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs +++ b/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs @@ -62,7 +62,7 @@ namespace Ryujinx.Ava.UI.Applet private void AvaloniaDynamicTextInputHandler_KeyRelease(object sender, KeyEventArgs e) { - var key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); + HidKey key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); if (!(KeyReleasedEvent?.Invoke(key)).GetValueOrDefault(true)) { @@ -82,7 +82,7 @@ namespace Ryujinx.Ava.UI.Applet private void AvaloniaDynamicTextInputHandler_KeyPressed(object sender, KeyEventArgs e) { - var key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); + HidKey key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); if (!(KeyPressedEvent?.Invoke(key)).GetValueOrDefault(true)) { diff --git a/src/Ryujinx/UI/Applet/AvaloniaHostUITheme.cs b/src/Ryujinx/UI/Applet/AvaloniaHostUITheme.cs index ea7a08bf7..553d6ef76 100644 --- a/src/Ryujinx/UI/Applet/AvaloniaHostUITheme.cs +++ b/src/Ryujinx/UI/Applet/AvaloniaHostUITheme.cs @@ -50,7 +50,7 @@ namespace Ryujinx.Ava.UI.Applet private string GetWindowsFontByLanguage() { - var culture = CultureInfo.CurrentUICulture; + CultureInfo culture = CultureInfo.CurrentUICulture; string langCode = culture.Name; return culture.TwoLetterISOLanguageName switch diff --git a/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs b/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs index a939d6ad9..8a0746113 100644 --- a/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs +++ b/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Ava.UI.Controls public void ToggleFavorite_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -59,14 +59,14 @@ namespace Ryujinx.Ava.UI.Controls public void OpenDeviceSaveDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; OpenSaveDirectory(viewModel, SaveDataType.Device, default); } public void OpenBcatSaveDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; OpenSaveDirectory(viewModel, SaveDataType.Bcat, default); } @@ -75,7 +75,7 @@ namespace Ryujinx.Ava.UI.Controls { if (viewModel?.SelectedApplication != null) { - var saveDataFilter = SaveDataFilter.Make(viewModel.SelectedApplication.Id, saveDataType, userId, saveDataId: default, index: default); + SaveDataFilter saveDataFilter = SaveDataFilter.Make(viewModel.SelectedApplication.Id, saveDataType, userId, saveDataId: default, index: default); ApplicationHelper.OpenSaveDir(in saveDataFilter, viewModel.SelectedApplication.Id, viewModel.SelectedApplication.ControlHolder, viewModel.SelectedApplication.Name); } @@ -83,7 +83,7 @@ namespace Ryujinx.Ava.UI.Controls public async void OpenTitleUpdateManager_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -93,7 +93,7 @@ namespace Ryujinx.Ava.UI.Controls public async void OpenDownloadableContentManager_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -103,7 +103,7 @@ namespace Ryujinx.Ava.UI.Controls public async void OpenCheatManager_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -117,7 +117,7 @@ namespace Ryujinx.Ava.UI.Controls public void OpenModsDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -130,7 +130,7 @@ namespace Ryujinx.Ava.UI.Controls public void OpenSdModsDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -143,7 +143,7 @@ namespace Ryujinx.Ava.UI.Controls public async void OpenModManager_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -157,7 +157,7 @@ namespace Ryujinx.Ava.UI.Controls public async void PurgePtcCache_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -251,7 +251,7 @@ namespace Ryujinx.Ava.UI.Controls public async void PurgeShaderCache_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -308,7 +308,7 @@ namespace Ryujinx.Ava.UI.Controls public void OpenPtcDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -329,7 +329,7 @@ namespace Ryujinx.Ava.UI.Controls public void OpenShaderCacheDirectory_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -346,7 +346,7 @@ namespace Ryujinx.Ava.UI.Controls public async void ExtractApplicationExeFs_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -360,7 +360,7 @@ namespace Ryujinx.Ava.UI.Controls public async void ExtractApplicationRomFs_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -374,7 +374,7 @@ namespace Ryujinx.Ava.UI.Controls public async void ExtractApplicationLogo_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication is { } selectedApp) { @@ -407,7 +407,7 @@ namespace Ryujinx.Ava.UI.Controls public void CreateApplicationShortcut_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -418,7 +418,7 @@ namespace Ryujinx.Ava.UI.Controls public async void RunApplication_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { @@ -428,7 +428,7 @@ namespace Ryujinx.Ava.UI.Controls public async void TrimXCI_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { diff --git a/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs b/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs index b0fd45e44..b2fd00182 100644 --- a/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs +++ b/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs @@ -1,5 +1,6 @@ using Avalonia.Controls; using Avalonia.Input; +using Avalonia.Input.Platform; using Avalonia.Interactivity; using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels; @@ -52,10 +53,10 @@ namespace Ryujinx.Ava.UI.Controls if (sender is not Button { Content: TextBlock idText }) return; - if (!App.IsClipboardAvailable(out var clipboard)) + if (!App.IsClipboardAvailable(out IClipboard clipboard)) return; - var appData = mwvm.Applications.FirstOrDefault(it => it.IdString == idText.Text); + ApplicationData appData = mwvm.Applications.FirstOrDefault(it => it.IdString == idText.Text); if (appData is null) return; diff --git a/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs b/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs index 1ca1615d5..460d972cb 100644 --- a/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs +++ b/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Ava.UI.Controls public static async Task Show(AccountManager ownerAccountManager, ContentManager ownerContentManager, VirtualFileSystem ownerVirtualFileSystem, HorizonClient ownerHorizonClient) { - var content = new NavigationDialogHost(ownerAccountManager, ownerContentManager, ownerVirtualFileSystem, ownerHorizonClient); + NavigationDialogHost content = new(ownerAccountManager, ownerContentManager, ownerVirtualFileSystem, ownerHorizonClient); ContentDialog contentDialog = new() { Title = LocaleManager.Instance[LocaleKeys.UserProfileWindowTitle], @@ -109,16 +109,16 @@ namespace Ryujinx.Ava.UI.Controls ViewModel.Profiles.Clear(); ViewModel.LostProfiles.Clear(); - var profiles = AccountManager.GetAllUsers().OrderBy(x => x.Name); + IOrderedEnumerable profiles = AccountManager.GetAllUsers().OrderBy(x => x.Name); - foreach (var profile in profiles) + foreach (HLE.HOS.Services.Account.Acc.UserProfile profile in profiles) { ViewModel.Profiles.Add(new UserProfile(profile, this)); } - var saveDataFilter = SaveDataFilter.Make(programId: default, saveType: SaveDataType.Account, default, saveDataId: default, index: default); + SaveDataFilter saveDataFilter = SaveDataFilter.Make(programId: default, saveType: SaveDataType.Account, default, saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new(); HorizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); @@ -137,8 +137,8 @@ namespace Ryujinx.Ava.UI.Controls for (int i = 0; i < readCount; i++) { - var save = saveDataInfo[i]; - var id = new UserId((long)save.UserId.Id.Low, (long)save.UserId.Id.High); + SaveDataInfo save = saveDataInfo[i]; + UserId id = new((long)save.UserId.Id.Low, (long)save.UserId.Id.High); if (ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId == id) == null) { lostAccounts.Add(id); @@ -146,7 +146,7 @@ namespace Ryujinx.Ava.UI.Controls } } - foreach (var account in lostAccounts) + foreach (UserId account in lostAccounts) { ViewModel.LostProfiles.Add(new UserProfile(new HLE.HOS.Services.Account.Acc.UserProfile(account, "", null), this)); } @@ -156,12 +156,12 @@ namespace Ryujinx.Ava.UI.Controls public async void DeleteUser(UserProfile userProfile) { - var lastUserId = AccountManager.LastOpenedUser.UserId; + UserId lastUserId = AccountManager.LastOpenedUser.UserId; if (userProfile.UserId == lastUserId) { // If we are deleting the currently open profile, then we must open something else before deleting. - var profile = ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId != lastUserId); + UserProfile profile = ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId != lastUserId); if (profile == null) { @@ -178,7 +178,7 @@ namespace Ryujinx.Ava.UI.Controls AccountManager.OpenUser(profile.UserId); } - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogUserProfileDeletionConfirmMessage], "", LocaleManager.Instance[LocaleKeys.InputDialogYes], diff --git a/src/Ryujinx/UI/Controls/SliderScroll.axaml.cs b/src/Ryujinx/UI/Controls/SliderScroll.axaml.cs index b57c6f0a2..db4d09336 100644 --- a/src/Ryujinx/UI/Controls/SliderScroll.axaml.cs +++ b/src/Ryujinx/UI/Controls/SliderScroll.axaml.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Ava.UI.Controls protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { - var newValue = Value + e.Delta.Y * TickFrequency; + double newValue = Value + e.Delta.Y * TickFrequency; if (newValue < Minimum) { diff --git a/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs b/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs index 48fe124e8..3344691f8 100644 --- a/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs +++ b/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Ava.UI.Helpers /// public static bool ReplaceWith(this AvaloniaList list, T item, bool addIfNotFound = true) { - var index = list.IndexOf(item); + int index = list.IndexOf(item); if (index != -1) { @@ -45,9 +45,9 @@ namespace Ryujinx.Ava.UI.Helpers /// The items to use as matching records to search for in the `sourceList', if not found this item will be added instead public static void AddOrReplaceMatching(this AvaloniaList list, IList sourceList, IList matchingList) { - foreach (var match in matchingList) + foreach (T match in matchingList) { - var index = sourceList.IndexOf(match); + int index = sourceList.IndexOf(match); if (index != -1) { list.ReplaceWith(sourceList[index]); diff --git a/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs b/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs index db604e038..a94588480 100644 --- a/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs +++ b/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs @@ -121,7 +121,7 @@ namespace Ryujinx.Ava.UI.Helpers startedDeferring = true; - var deferral = args.GetDeferral(); + ContentDialogButtonClickDeferral deferral = args.GetDeferral(); sender.PrimaryButtonClick -= DeferClose; diff --git a/src/Ryujinx/UI/Helpers/GlyphValueConverter.cs b/src/Ryujinx/UI/Helpers/GlyphValueConverter.cs index 1544d33ae..a3e4e5a4c 100644 --- a/src/Ryujinx/UI/Helpers/GlyphValueConverter.cs +++ b/src/Ryujinx/UI/Helpers/GlyphValueConverter.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Ava.UI.Helpers { get { - if (_glyphs.TryGetValue(Enum.Parse(key), out var val)) + if (_glyphs.TryGetValue(Enum.Parse(key), out string val)) { return val; } diff --git a/src/Ryujinx/UI/Helpers/LoggerAdapter.cs b/src/Ryujinx/UI/Helpers/LoggerAdapter.cs index fc7145410..7dff4b8fd 100644 --- a/src/Ryujinx/UI/Helpers/LoggerAdapter.cs +++ b/src/Ryujinx/UI/Helpers/LoggerAdapter.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Ava.UI.Helpers private static string Format(AvaLogLevel level, string area, string template, object source, object[] v) { - var result = new StringBuilder(); + StringBuilder result = new(); var r = new CharacterReader(template.AsSpan()); int i = 0; diff --git a/src/Ryujinx/UI/Helpers/NotificationHelper.cs b/src/Ryujinx/UI/Helpers/NotificationHelper.cs index eab075806..2bc0b4a68 100644 --- a/src/Ryujinx/UI/Helpers/NotificationHelper.cs +++ b/src/Ryujinx/UI/Helpers/NotificationHelper.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Ava.UI.Helpers public static void Show(string title, string text, NotificationType type, bool waitingExit = false, Action onClick = null, Action onClose = null) { - var delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs); + TimeSpan delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs); _notifications.Add(new Notification(title, text, type, delay, onClick, onClose)); } diff --git a/src/Ryujinx/UI/Helpers/TimeZoneConverter.cs b/src/Ryujinx/UI/Helpers/TimeZoneConverter.cs index 876d51f71..50b11fce5 100644 --- a/src/Ryujinx/UI/Helpers/TimeZoneConverter.cs +++ b/src/Ryujinx/UI/Helpers/TimeZoneConverter.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.UI.Helpers return null; } - var timeZone = (TimeZone)value; + TimeZone timeZone = (TimeZone)value; return string.Format("{0} {1} {2}", timeZone.UtcDifference, timeZone.Location, timeZone.Abbreviation); } diff --git a/src/Ryujinx/UI/Helpers/UserErrorDialog.cs b/src/Ryujinx/UI/Helpers/UserErrorDialog.cs index 9a44b862b..2859a9647 100644 --- a/src/Ryujinx/UI/Helpers/UserErrorDialog.cs +++ b/src/Ryujinx/UI/Helpers/UserErrorDialog.cs @@ -74,7 +74,7 @@ namespace Ryujinx.Ava.UI.Helpers string setupButtonLabel = isInSetupGuide ? LocaleManager.Instance[LocaleKeys.OpenSetupGuideMessage] : ""; - var result = await ContentDialogHelper.CreateInfoDialog( + UserResult result = await ContentDialogHelper.CreateInfoDialog( LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogUserErrorDialogMessage, errorCode, GetErrorTitle(error)), GetErrorDescription(error) + (isInSetupGuide ? LocaleManager.Instance[LocaleKeys.DialogUserErrorDialogInfoMessage] diff --git a/src/Ryujinx/UI/Models/CheatNode.cs b/src/Ryujinx/UI/Models/CheatNode.cs index 9179fb0ef..b036ba6b9 100644 --- a/src/Ryujinx/UI/Models/CheatNode.cs +++ b/src/Ryujinx/UI/Models/CheatNode.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.UI.Models } set { - foreach (var cheat in SubNodes) + foreach (CheatNode cheat in SubNodes) { cheat.IsEnabled = value; cheat.OnPropertyChanged(); diff --git a/src/Ryujinx/UI/Models/Input/GamepadInputConfig.cs b/src/Ryujinx/UI/Models/Input/GamepadInputConfig.cs index c03f58a22..3571f56e9 100644 --- a/src/Ryujinx/UI/Models/Input/GamepadInputConfig.cs +++ b/src/Ryujinx/UI/Models/Input/GamepadInputConfig.cs @@ -488,7 +488,7 @@ namespace Ryujinx.Ava.UI.Models.Input public InputConfig GetConfig() { - var config = new StandardControllerInputConfig + StandardControllerInputConfig config = new() { Id = Id, Backend = InputBackendType.GamepadSDL3, diff --git a/src/Ryujinx/UI/Models/Input/HotkeyConfig.cs b/src/Ryujinx/UI/Models/Input/HotkeyConfig.cs index 4c7a6bd02..d8a2835ee 100644 --- a/src/Ryujinx/UI/Models/Input/HotkeyConfig.cs +++ b/src/Ryujinx/UI/Models/Input/HotkeyConfig.cs @@ -146,7 +146,7 @@ namespace Ryujinx.Ava.UI.Models.Input public KeyboardHotkeys GetConfig() { - var config = new KeyboardHotkeys + KeyboardHotkeys config = new() { ToggleVSyncMode = ToggleVSyncMode, Screenshot = Screenshot, diff --git a/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs b/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs index 66f1f62a2..a71c85eba 100644 --- a/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs +++ b/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs @@ -367,7 +367,7 @@ namespace Ryujinx.Ava.UI.Models.Input public InputConfig GetConfig() { - var config = new StandardKeyboardInputConfig + StandardKeyboardInputConfig config = new() { Id = Id, Backend = InputBackendType.WindowKeyboard, diff --git a/src/Ryujinx/UI/Models/SaveModel.cs b/src/Ryujinx/UI/Models/SaveModel.cs index b8e5fd868..6ab9af3e8 100644 --- a/src/Ryujinx/UI/Models/SaveModel.cs +++ b/src/Ryujinx/UI/Models/SaveModel.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Ava.UI.Models TitleId = info.ProgramId; UserId = info.UserId; - var appData = MainWindow.MainWindowViewModel.Applications.FirstOrDefault(x => x.IdString.ToUpper() == TitleIdString); + ApplicationData appData = MainWindow.MainWindowViewModel.Applications.FirstOrDefault(x => x.IdString.ToUpper() == TitleIdString); InGameList = appData != null; @@ -70,7 +70,7 @@ namespace Ryujinx.Ava.UI.Models Task.Run(() => { - var saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); + string saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); long totalSize = GetDirectorySize(saveRoot); @@ -79,14 +79,14 @@ namespace Ryujinx.Ava.UI.Models long size = 0; if (Directory.Exists(path)) { - var directories = Directory.GetDirectories(path); - foreach (var directory in directories) + string[] directories = Directory.GetDirectories(path); + foreach (string directory in directories) { size += GetDirectorySize(directory); } - var files = Directory.GetFiles(path); - foreach (var file in files) + string[] files = Directory.GetFiles(path); + foreach (string file in files) { size += new FileInfo(file).Length; } diff --git a/src/Ryujinx/UI/Models/UserProfile.cs b/src/Ryujinx/UI/Models/UserProfile.cs index 9cf8c10a2..cc46ff593 100644 --- a/src/Ryujinx/UI/Models/UserProfile.cs +++ b/src/Ryujinx/UI/Models/UserProfile.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Media; using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.ViewModels; @@ -87,7 +88,7 @@ namespace Ryujinx.Ava.UI.Models private void UpdateBackground() { - var currentApplication = Avalonia.Application.Current; + Application currentApplication = Avalonia.Application.Current; object color = null; currentApplication?.Styles.TryGetResource("ControlFillColorSecondary", currentApplication.ActualThemeVariant, out color); diff --git a/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs b/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs index 3842301de..7f3e2bdcc 100644 --- a/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs +++ b/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs @@ -44,13 +44,13 @@ namespace Ryujinx.Ava.UI.Renderer throw new PlatformNotSupportedException(); } - var flags = OpenGLContextFlags.Compat; + OpenGLContextFlags flags = OpenGLContextFlags.Compat; if (ConfigurationState.Instance.Logger.GraphicsDebugLevel != GraphicsDebugLevel.None) { flags |= OpenGLContextFlags.Debug; } - var graphicsMode = Environment.OSVersion.Platform == PlatformID.Unix ? new FramebufferFormat(new ColorFormat(8, 8, 8, 0), 16, 0, ColorFormat.Zero, 0, 2, false) : FramebufferFormat.Default; + FramebufferFormat graphicsMode = Environment.OSVersion.Platform == PlatformID.Unix ? new FramebufferFormat(new ColorFormat(8, 8, 8, 0), 16, 0, ColorFormat.Zero, 0, 2, false) : FramebufferFormat.Default; Context = PlatformHelper.CreateOpenGLContext(graphicsMode, 3, 3, flags); diff --git a/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs b/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs index 7bcc4bdd2..41b3b8c4a 100644 --- a/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadDownloadableContents() { - var dlcs = _applicationLibrary.DownloadableContents.Items + IEnumerable<(DownloadableContentModel Dlc, bool IsEnabled)> dlcs = _applicationLibrary.DownloadableContents.Items .Where(it => it.Dlc.TitleIdBase == _applicationData.IdBase); bool hasBundledContent = false; @@ -136,7 +136,7 @@ namespace Ryujinx.Ava.UI.ViewModels // NOTE(jpr): this works around a bug where calling _views.Clear also clears SelectedDownloadableContents for // some reason. so we save the items here and add them back after - var items = SelectedDownloadableContents.ToArray(); + DownloadableContentModel[] items = SelectedDownloadableContents.ToArray(); _views.Clear(); _views.AddRange(view); @@ -176,10 +176,10 @@ namespace Ryujinx.Ava.UI.ViewModels }, }); - var totalDlcAdded = 0; + int totalDlcAdded = 0; foreach (var file in result) { - if (!AddDownloadableContent(file.Path.LocalPath, out var newDlcAdded)) + if (!AddDownloadableContent(file.Path.LocalPath, out int newDlcAdded)) { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogDlcNoDlcErrorMessage]); } @@ -202,18 +202,18 @@ namespace Ryujinx.Ava.UI.ViewModels return false; } - if (!_applicationLibrary.TryGetDownloadableContentFromFile(path, out var dlcs) || dlcs.Count == 0) + if (!_applicationLibrary.TryGetDownloadableContentFromFile(path, out List dlcs) || dlcs.Count == 0) { return false; } - var dlcsForThisGame = dlcs.Where(it => it.TitleIdBase == _applicationData.IdBase).ToList(); + List dlcsForThisGame = dlcs.Where(it => it.TitleIdBase == _applicationData.IdBase).ToList(); if (dlcsForThisGame.Count == 0) { return false; } - foreach (var dlc in dlcsForThisGame) + foreach (DownloadableContentModel dlc in dlcsForThisGame) { if (!DownloadableContents.Contains(dlc)) { @@ -277,13 +277,13 @@ namespace Ryujinx.Ava.UI.ViewModels public void Save() { - var dlcs = DownloadableContents.Select(it => (it, SelectedDownloadableContents.Contains(it))).ToList(); + List<(DownloadableContentModel it, bool)> dlcs = DownloadableContents.Select(it => (it, SelectedDownloadableContents.Contains(it))).ToList(); _applicationLibrary.SaveDownloadableContentsForGame(_applicationData, dlcs); } private Task ShowNewDlcAddedDialog(int numAdded) { - var msg = string.Format(LocaleManager.Instance[LocaleKeys.DlcWindowDlcAddedMessage], numAdded); + string msg = string.Format(LocaleManager.Instance[LocaleKeys.DlcWindowDlcAddedMessage], numAdded); return Dispatcher.UIThread.InvokeAsync(async () => { await ContentDialogHelper.ShowTextDialog(LocaleManager.Instance[LocaleKeys.DialogConfirmationTitle], msg, "", "", "", LocaleManager.Instance[LocaleKeys.InputDialogOk], (int)Symbol.Checkmark); diff --git a/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs b/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs index ec3b93e88..9c300dfd9 100644 --- a/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs @@ -225,7 +225,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input return; } - var selected = Devices[_device].Type; + DeviceType selected = Devices[_device].Type; if (selected != DeviceType.None) { @@ -315,7 +315,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } else { - var type = DeviceType.None; + DeviceType type = DeviceType.None; if (Config is StandardKeyboardInputConfig) { @@ -327,7 +327,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input type = DeviceType.Controller; } - var item = Devices.FirstOrDefault(x => x.Type == type && x.Id == Config.Id); + (DeviceType Type, string Id, string Name) item = Devices.FirstOrDefault(x => x.Type == type && x.Id == Config.Id); if (item != default) { Device = Devices.ToList().FindIndex(x => x.Id == item.Id); @@ -347,7 +347,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } string id = GetCurrentGamepadId(); - var type = Devices[Device].Type; + DeviceType type = Devices[Device].Type; if (type == DeviceType.None) { @@ -395,7 +395,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input return string.Empty; } - var device = Devices[Device]; + (DeviceType Type, string Id, string Name) device = Devices[Device]; if (device.Type == DeviceType.None) { @@ -517,7 +517,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input private string GetProfileBasePath() { string path = AppDataManager.ProfilesDirPath; - var type = Devices[Device == -1 ? 0 : Device].Type; + DeviceType type = Devices[Device == -1 ? 0 : Device].Type; if (type == DeviceType.Keyboard) { @@ -557,7 +557,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input public InputConfig LoadDefaultConfiguration() { - var activeDevice = Devices.FirstOrDefault(); + (DeviceType Type, string Id, string Name) activeDevice = Devices.FirstOrDefault(); if (Devices.Count > 0 && Device < Devices.Count && Device >= 0) { @@ -857,20 +857,20 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } else { - var device = Devices[Device]; + (DeviceType Type, string Id, string Name) device = Devices[Device]; if (device.Type == DeviceType.Keyboard) { - var inputConfig = ((KeyboardInputViewModel)ConfigViewModel).Config; + KeyboardInputConfig inputConfig = ((KeyboardInputViewModel)ConfigViewModel).Config; inputConfig.Id = device.Id; } else { - var inputConfig = ((ControllerInputViewModel)ConfigViewModel).Config; + GamepadInputConfig inputConfig = ((ControllerInputViewModel)ConfigViewModel).Config; inputConfig.Id = device.Id.Split(" ")[0]; } - var config = !IsController + InputConfig config = !IsController ? ((KeyboardInputViewModel)ConfigViewModel).Config.GetConfig() : ((ControllerInputViewModel)ConfigViewModel).Config.GetConfig(); config.ControllerType = Controllers[_controller].Type; diff --git a/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs b/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs index 7d6962c97..f12f4cde8 100644 --- a/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs @@ -1230,9 +1230,9 @@ namespace Ryujinx.Ava.UI.ViewModels appsCopy = new List(Applications); } - var tempApplications = new List(); + List tempApplications = new(); - foreach (var app in appsCopy) + foreach (ApplicationData app in appsCopy) { if (Filter(app)) { @@ -1242,7 +1242,7 @@ namespace Ryujinx.Ava.UI.ViewModels tempApplications.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - foreach (var application in tempApplications) + foreach (ApplicationData application in tempApplications) { try { @@ -1655,9 +1655,9 @@ namespace Ryujinx.Ava.UI.ViewModels if (result.Count > 0) { var dirs = result.Select(it => it.Path.LocalPath).ToList(); - var numAdded = onDirsSelected(dirs, out int numRemoved); + int numAdded = onDirsSelected(dirs, out int numRemoved); - var msg = String.Join("\r\n", new string[] { + string msg = String.Join("\r\n", new string[] { string.Format(LocaleManager.Instance[localeMessageRemovedKey], numRemoved), string.Format(LocaleManager.Instance[localeMessageAddedKey], numAdded) }); @@ -1689,17 +1689,17 @@ namespace Ryujinx.Ava.UI.ViewModels public void LoadConfigurableHotKeys() { - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI, out var showUiKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI, out Avalonia.Input.Key showUiKey)) { ShowUiKey = new KeyGesture(showUiKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out Avalonia.Input.Key screenshotKey)) { ScreenshotKey = new KeyGesture(screenshotKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out Avalonia.Input.Key pauseKey)) { PauseKey = new KeyGesture(pauseKey); } @@ -2081,7 +2081,7 @@ namespace Ryujinx.Ava.UI.ViewModels this, TopLevel); - CancellationTokenSource cts = new CancellationTokenSource(); + CancellationTokenSource cts = new(); try { @@ -2370,16 +2370,16 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - var trimmer = new XCIFileTrimmer(filename, new XCIFileTrimmerMainWindowLog(this)); + XCIFileTrimmer trimmer = new(filename, new XCIFileTrimmerMainWindowLog(this)); if (trimmer.CanBeTrimmed) { - var savings = (double)trimmer.DiskSpaceSavingsB / 1024.0 / 1024.0; - var currentFileSize = (double)trimmer.FileSizeB / 1024.0 / 1024.0; - var cartDataSize = (double)trimmer.DataSizeB / 1024.0 / 1024.0; + double savings = (double)trimmer.DiskSpaceSavingsB / 1024.0 / 1024.0; + double currentFileSize = (double)trimmer.FileSizeB / 1024.0 / 1024.0; + double cartDataSize = (double)trimmer.DataSizeB / 1024.0 / 1024.0; string secondaryText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.TrimXCIFileDialogSecondaryText, currentFileSize, cartDataSize, savings); - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.TrimXCIFileDialogPrimaryText], secondaryText, LocaleManager.Instance[LocaleKeys.Continue], diff --git a/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs b/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs index 18bf53b22..e3ff44f96 100644 --- a/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs @@ -107,37 +107,37 @@ namespace Ryujinx.Ava.UI.ViewModels string[] modsBasePaths = [ModLoader.GetSdModsBasePath(), ModLoader.GetModsBasePath()]; - foreach (var path in modsBasePaths) + foreach (string path in modsBasePaths) { - var inSd = path == ModLoader.GetSdModsBasePath(); - var modCache = new ModLoader.ModCache(); + bool inSd = path == ModLoader.GetSdModsBasePath(); + ModLoader.ModCache modCache = new(); ModLoader.QueryContentsDir(modCache, new DirectoryInfo(Path.Combine(path, "contents")), applicationId, _installedDlcIds); - foreach (var mod in modCache.RomfsDirs) + foreach (ModLoader.Mod mod in modCache.RomfsDirs) { - var modModel = new ModModel(mod.Path.Parent?.FullName, mod.Name, mod.Enabled, inSd); + ModModel modModel = new(mod.Path.Parent?.FullName, mod.Name, mod.Enabled, inSd); if (Mods.All(x => x.Path != mod.Path.Parent?.FullName)) { Mods.Add(modModel); } } - foreach (var mod in modCache.RomfsContainers) + foreach (ModLoader.Mod mod in modCache.RomfsContainers) { Mods.Add(new ModModel(mod.Path.FullName, mod.Name, mod.Enabled, inSd)); } - foreach (var mod in modCache.ExefsDirs) + foreach (ModLoader.Mod mod in modCache.ExefsDirs) { - var modModel = new ModModel(mod.Path.Parent?.FullName, mod.Name, mod.Enabled, inSd); + ModModel modModel = new(mod.Path.Parent?.FullName, mod.Name, mod.Enabled, inSd); if (Mods.All(x => x.Path != mod.Path.Parent?.FullName)) { Mods.Add(modModel); } } - foreach (var mod in modCache.ExefsContainers) + foreach (ModLoader.Mod mod in modCache.ExefsContainers) { Mods.Add(new ModModel(mod.Path.FullName, mod.Name, mod.Enabled, inSd)); } @@ -191,10 +191,10 @@ namespace Ryujinx.Ava.UI.ViewModels public void Delete(ModModel model, bool removeFromList = true) { - var isSubdir = true; - var pathToDelete = model.Path; - var basePath = model.InSd ? ModLoader.GetSdModsBasePath() : ModLoader.GetModsBasePath(); - var modsDir = ModLoader.GetApplicationDir(basePath, _applicationId.ToString("x16")); + bool isSubdir = true; + string pathToDelete = model.Path; + string basePath = model.InSd ? ModLoader.GetSdModsBasePath() : ModLoader.GetModsBasePath(); + string modsDir = ModLoader.GetApplicationDir(basePath, _applicationId.ToString("x16")); if (new DirectoryInfo(model.Path).Parent?.FullName == modsDir) { @@ -203,9 +203,9 @@ namespace Ryujinx.Ava.UI.ViewModels if (isSubdir) { - var parentDir = String.Empty; + string parentDir = String.Empty; - foreach (var dir in Directory.GetDirectories(modsDir, "*", SearchOption.TopDirectoryOnly)) + foreach (string dir in Directory.GetDirectories(modsDir, "*", SearchOption.TopDirectoryOnly)) { if (Directory.GetDirectories(dir, "*", SearchOption.AllDirectories).Contains(model.Path)) { @@ -257,10 +257,10 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - var destinationDir = ModLoader.GetApplicationDir(ModLoader.GetSdModsBasePath(), _applicationId.ToString("x16")); + string destinationDir = ModLoader.GetApplicationDir(ModLoader.GetSdModsBasePath(), _applicationId.ToString("x16")); // TODO: More robust checking for valid mod folders - var isDirectoryValid = directories.Length != 0; + bool isDirectoryValid = directories.Length != 0; if (!isDirectoryValid) { @@ -271,7 +271,7 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - foreach (var dir in directories) + foreach (string dir in directories) { string dirToCreate = dir.Replace(directory.Parent?.ToString() ?? string.Empty, destinationDir); @@ -292,9 +292,9 @@ namespace Ryujinx.Ava.UI.ViewModels Directory.CreateDirectory(dirToCreate); } - var files = Directory.GetFiles(directory.ToString(), "*", SearchOption.AllDirectories); + string[] files = Directory.GetFiles(directory.ToString(), "*", SearchOption.AllDirectories); - foreach (var file in files) + foreach (string file in files) { File.Copy(file, file.Replace(directory.Parent?.ToString() ?? string.Empty, destinationDir), true); } @@ -318,7 +318,7 @@ namespace Ryujinx.Ava.UI.ViewModels public void DeleteAll() { - foreach (var it in Mods) Delete(it, false); + foreach (ModModel it in Mods) Delete(it, false); Mods.Clear(); OnPropertyChanged(nameof(ModCount)); Sort(); diff --git a/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs b/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs index 4a6fc06f0..5e8008cd8 100644 --- a/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs @@ -13,6 +13,7 @@ using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration.Multiplayer; using Ryujinx.Common.GraphicsDriver; using Ryujinx.Common.Logging; +using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Vulkan; using Ryujinx.HLE; using Ryujinx.HLE.FileSystem; @@ -27,7 +28,10 @@ using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading.Tasks; +using AntiAliasing = Ryujinx.Common.Configuration.AntiAliasing; +using ScalingFilter = Ryujinx.Common.Configuration.ScalingFilter; using TimeZone = Ryujinx.Ava.UI.Models.TimeZone; +using VSyncMode = Ryujinx.Common.Configuration.VSyncMode; namespace Ryujinx.Ava.UI.ViewModels { @@ -441,7 +445,7 @@ namespace Ryujinx.Ava.UI.ViewModels { AvailableGpus.Clear(); - var devices = VulkanRenderer.GetPhysicalDevices(); + DeviceInfo[] devices = VulkanRenderer.GetPhysicalDevices(); if (devices.Length == 0) { @@ -450,7 +454,7 @@ namespace Ryujinx.Ava.UI.ViewModels } else { - foreach (var device in devices) + foreach (DeviceInfo device in devices) { await Dispatcher.UIThread.InvokeAsync(() => { diff --git a/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs b/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs index debfe6e3d..b0b185610 100644 --- a/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs @@ -85,7 +85,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadUpdates() { - var updates = ApplicationLibrary.TitleUpdates.Items + IEnumerable<(TitleUpdateModel TitleUpdate, bool IsSelected)> updates = ApplicationLibrary.TitleUpdates.Items .Where(it => it.TitleUpdate.TitleIdBase == ApplicationData.IdBase); bool hasBundledContent = false; @@ -108,11 +108,11 @@ namespace Ryujinx.Ava.UI.ViewModels public void SortUpdates() { - var sortedUpdates = TitleUpdates.OrderByDescending(update => update.Version); + IOrderedEnumerable sortedUpdates = TitleUpdates.OrderByDescending(update => update.Version); // NOTE(jpr): this works around a bug where calling Views.Clear also clears SelectedUpdate for // some reason. so we save the item here and restore it after - var selected = SelectedUpdate; + object selected = SelectedUpdate; Views.Clear(); Views.Add(new TitleUpdateViewNoUpdateSentinal()); @@ -140,18 +140,18 @@ namespace Ryujinx.Ava.UI.ViewModels return false; } - if (!ApplicationLibrary.TryGetTitleUpdatesFromFile(path, out var updates)) + if (!ApplicationLibrary.TryGetTitleUpdatesFromFile(path, out List updates)) { return false; } - var updatesForThisGame = updates.Where(it => it.TitleIdBase == ApplicationData.Id).ToList(); + List updatesForThisGame = updates.Where(it => it.TitleIdBase == ApplicationData.Id).ToList(); if (updatesForThisGame.Count == 0) { return false; } - foreach (var update in updatesForThisGame) + foreach (TitleUpdateModel update in updatesForThisGame) { if (!TitleUpdates.Contains(update)) { @@ -200,10 +200,10 @@ namespace Ryujinx.Ava.UI.ViewModels }, }); - var totalUpdatesAdded = 0; + int totalUpdatesAdded = 0; foreach (var file in result) { - if (!AddUpdate(file.Path.LocalPath, out var newUpdatesAdded)) + if (!AddUpdate(file.Path.LocalPath, out int newUpdatesAdded)) { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogUpdateAddUpdateErrorMessage]); } @@ -219,13 +219,13 @@ namespace Ryujinx.Ava.UI.ViewModels public void Save() { - var updates = TitleUpdates.Select(it => (it, it == SelectedUpdate as TitleUpdateModel)).ToList(); + List<(TitleUpdateModel it, bool)> updates = TitleUpdates.Select(it => (it, it == SelectedUpdate as TitleUpdateModel)).ToList(); ApplicationLibrary.SaveTitleUpdatesForGame(ApplicationData, updates); } private Task ShowNewUpdatesAddedDialog(int numAdded) { - var msg = string.Format(LocaleManager.Instance[LocaleKeys.UpdateWindowUpdateAddedMessage], numAdded); + string msg = string.Format(LocaleManager.Instance[LocaleKeys.UpdateWindowUpdateAddedMessage], numAdded); return Dispatcher.UIThread.InvokeAsync(async () => { await ContentDialogHelper.ShowTextDialog(LocaleManager.Instance[LocaleKeys.DialogConfirmationTitle], msg, "", "", "", LocaleManager.Instance[LocaleKeys.InputDialogOk], (int)Symbol.Checkmark); diff --git a/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs b/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs index 468c7334d..005fa26f7 100644 --- a/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs @@ -83,7 +83,7 @@ namespace Ryujinx.Ava.UI.ViewModels { Images.Clear(); - foreach (var image in _avatarStore) + foreach (KeyValuePair image in _avatarStore) { Images.Add(new ProfileImageModel(image.Key, image.Value)); } @@ -91,7 +91,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void ChangeImageBackground() { - foreach (var image in Images) + foreach (ProfileImageModel image in Images) { image.BackgroundColor = new SolidColorBrush(BackgroundColor); } @@ -119,7 +119,7 @@ namespace Ryujinx.Ava.UI.ViewModels // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) { - using var file = new UniqueRef(); + using UniqueRef file = new(); romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs b/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs index 918d392d6..f854dbde6 100644 --- a/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs @@ -56,10 +56,10 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadXCIApplications() { - var apps = _applicationLibrary.Applications.Items + IEnumerable apps = _applicationLibrary.Applications.Items .Where(app => app.FileExtension == _FileExtXCI); - foreach (var xciApp in apps) + foreach (ApplicationData xciApp in apps) AddOrUpdateXCITrimmerFile(CreateXCITrimmerFile(xciApp.Path)); ApplicationsChanged(); @@ -69,7 +69,7 @@ namespace Ryujinx.Ava.UI.ViewModels string path, OperationOutcome operationOutcome = OperationOutcome.Undetermined) { - var xciApp = _applicationLibrary.Applications.Items.First(app => app.FileExtension == _FileExtXCI && app.Path == path); + ApplicationData xciApp = _applicationLibrary.Applications.Items.First(app => app.FileExtension == _FileExtXCI && app.Path == path); return XCITrimmerFileModel.FromApplicationData(xciApp, _logger) with { ProcessingOutcome = operationOutcome }; } @@ -154,17 +154,17 @@ namespace Ryujinx.Ava.UI.ViewModels _processingMode = processingMode; Processing = true; - var cancellationToken = _cancellationTokenSource.Token; + CancellationToken cancellationToken = _cancellationTokenSource.Token; Thread XCIFileTrimThread = new(() => { - var toProcess = Sort(SelectedXCIFiles + List toProcess = Sort(SelectedXCIFiles .Where(xci => (processingMode == ProcessingMode.Untrimming && xci.Untrimmable) || (processingMode == ProcessingMode.Trimming && xci.Trimmable) )).ToList(); - var viewsSaved = DisplayedXCIFiles.ToList(); + List viewsSaved = DisplayedXCIFiles.ToList(); Dispatcher.UIThread.Post(() => { @@ -175,19 +175,19 @@ namespace Ryujinx.Ava.UI.ViewModels try { - foreach (var xciApp in toProcess) + foreach (XCITrimmerFileModel xciApp in toProcess) { if (cancellationToken.IsCancellationRequested) break; - var trimmer = new XCIFileTrimmer(xciApp.Path, _logger); + XCIFileTrimmer trimmer = new(xciApp.Path, _logger); Dispatcher.UIThread.Post(() => { ProcessingApplication = xciApp; }); - var outcome = OperationOutcome.Undetermined; + OperationOutcome outcome = OperationOutcome.Undetermined; try { diff --git a/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs index afe41259d..eeabc6f93 100644 --- a/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs @@ -9,6 +9,7 @@ using Ryujinx.Ava.UI.ViewModels.Input; using Ryujinx.Common.Configuration.Hid.Controller; using Ryujinx.Input; using Ryujinx.Input.Assigner; +using Button = Ryujinx.Input.Button; using StickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId; namespace Ryujinx.Ava.UI.Views.Input @@ -129,7 +130,7 @@ namespace Ryujinx.Ava.UI.Views.Input { if (e.ButtonValue.HasValue) { - var buttonValue = e.ButtonValue.Value; + Button buttonValue = e.ButtonValue.Value; viewModel.ParentModel.IsModified = true; switch (button.Name) diff --git a/src/Ryujinx/UI/Views/Input/InputView.axaml.cs b/src/Ryujinx/UI/Views/Input/InputView.axaml.cs index 3803d7fc7..b0de81448 100644 --- a/src/Ryujinx/UI/Views/Input/InputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/InputView.axaml.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Ava.UI.Views.Input { _dialogOpen = true; - var result = await ContentDialogHelper.CreateConfirmationDialogExtended( + UserResult result = await ContentDialogHelper.CreateConfirmationDialogExtended( LocaleManager.Instance[LocaleKeys.DialogControllerSettingsModifiedConfirmMessage], LocaleManager.Instance[LocaleKeys.DialogControllerSettingsModifiedConfirmSubMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -71,7 +71,7 @@ namespace Ryujinx.Ava.UI.Views.Input if (e.AddedItems.Count > 0) { ViewModel.IsModified = true; - var player = (PlayerModel)e.AddedItems[0]; + PlayerModel player = (PlayerModel)e.AddedItems[0]; if (player != null) { ViewModel.PlayerId = player.Id; diff --git a/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs index acc1ebe4d..e855c2055 100644 --- a/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs @@ -8,6 +8,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels.Input; using Ryujinx.Input; using Ryujinx.Input.Assigner; +using Button = Ryujinx.Input.Button; using Key = Ryujinx.Common.Configuration.Hid.Key; namespace Ryujinx.Ava.UI.Views.Input @@ -58,7 +59,7 @@ namespace Ryujinx.Ava.UI.Views.Input PointerPressed += MouseClick; - var viewModel = (DataContext as KeyboardInputViewModel); + KeyboardInputViewModel viewModel = (DataContext as KeyboardInputViewModel); if (viewModel != null) { @@ -69,7 +70,7 @@ namespace Ryujinx.Ava.UI.Views.Input { if (e.ButtonValue.HasValue) { - var buttonValue = e.ButtonValue.Value; + Button buttonValue = e.ButtonValue.Value; viewModel.ParentModel.IsModified = true; switch (button.Name) diff --git a/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs index 3e12d9de8..7d61fcf8c 100644 --- a/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; +using Ryujinx.Ava.UI.Models.Input; using Ryujinx.Ava.UI.ViewModels.Input; using System.Threading.Tasks; @@ -17,7 +18,7 @@ namespace Ryujinx.Ava.UI.Views.Input public MotionInputView(ControllerInputViewModel viewModel) { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; _viewModel = new MotionInputViewModel { @@ -49,7 +50,7 @@ namespace Ryujinx.Ava.UI.Views.Input }; contentDialog.PrimaryButtonClick += (_, _) => { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; config.Slot = content._viewModel.Slot; config.Sensitivity = content._viewModel.Sensitivity; config.GyroDeadzone = content._viewModel.GyroDeadzone; diff --git a/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs index 82872efa1..6a19d8f10 100644 --- a/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; +using Ryujinx.Ava.UI.Models.Input; using Ryujinx.Ava.UI.ViewModels.Input; using System.Threading.Tasks; @@ -17,7 +18,7 @@ namespace Ryujinx.Ava.UI.Views.Input public RumbleInputView(ControllerInputViewModel viewModel) { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; _viewModel = new RumbleInputViewModel { @@ -45,7 +46,7 @@ namespace Ryujinx.Ava.UI.Views.Input contentDialog.PrimaryButtonClick += (_, _) => { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; config.StrongRumble = content._viewModel.StrongRumble; config.WeakRumble = content._viewModel.WeakRumble; }; diff --git a/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs b/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs index ea99f8df0..cc78ad83b 100644 --- a/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs +++ b/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs @@ -40,7 +40,7 @@ namespace Ryujinx.Ava.UI.Views.Main { List checkBoxes = []; - foreach (var item in Enum.GetValues(typeof(FileTypes))) + foreach (object item in Enum.GetValues(typeof(FileTypes))) { string fileName = Enum.GetName(typeof(FileTypes), item); checkBoxes.Add(new CheckBox @@ -69,7 +69,7 @@ namespace Ryujinx.Ava.UI.Views.Main { string languageCode = Path.GetFileNameWithoutExtension(locale).Split('.').Last(); string languageJson = EmbeddedResources.ReadAllText($"{localePath}/{languageCode}{localeExt}"); - var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); + Dictionary strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); if (!strings.TryGetValue("Language", out string languageName)) { diff --git a/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs b/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs index 233927cc5..4bf3e0d27 100644 --- a/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs +++ b/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs @@ -8,6 +8,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Input; using Ryujinx.Input.Assigner; +using Button = Ryujinx.Input.Button; using Key = Ryujinx.Common.Configuration.Hid.Key; namespace Ryujinx.Ava.UI.Views.Settings @@ -59,15 +60,15 @@ namespace Ryujinx.Ava.UI.Views.Settings this.Focus(NavigationMethod.Pointer); - var keyboard = (IKeyboard)_avaloniaKeyboardDriver.GetGamepad("0"); + IKeyboard keyboard = (IKeyboard)_avaloniaKeyboardDriver.GetGamepad("0"); IButtonAssigner assigner = new KeyboardKeyAssigner(keyboard); _currentAssigner.ButtonAssigned += (_, e) => { if (e.ButtonValue.HasValue) { - var viewModel = (DataContext) as SettingsViewModel; - var buttonValue = e.ButtonValue.Value; + SettingsViewModel viewModel = (DataContext) as SettingsViewModel; + Button buttonValue = e.ButtonValue.Value; if (viewModel != null) { diff --git a/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs index 543af912d..d91d6f257 100644 --- a/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs @@ -39,7 +39,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var (parent, profile, isNewUser) = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; + (NavigationDialogHost parent, UserProfile profile, bool isNewUser) = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; _isNewUser = isNewUser; _profile = profile; TempProfile = new TempProfile(_profile); diff --git a/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs index 3bb49d725..06a3005a0 100644 --- a/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs @@ -66,7 +66,7 @@ namespace Ryujinx.Ava.UI.Views.User { if (ViewModel.SelectedImage != null) { - using var streamJpg = new MemoryStream(); + using MemoryStream streamJpg = new(); using var bitmap = SKBitmap.Decode(ViewModel.SelectedImage); using var newBitmap = new SKBitmap(bitmap.Width, bitmap.Height); diff --git a/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs index 51d98ac27..cb3409992 100644 --- a/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs @@ -111,7 +111,7 @@ namespace Ryujinx.Ava.UI.Views.User var resizedBitmap = bitmap.Resize(new SKImageInfo(256, 256), SKFilterQuality.High); - using var streamJpg = new MemoryStream(); + using MemoryStream streamJpg = new(); if (resizedBitmap != null) { diff --git a/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs b/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs index 1cca308f7..e79ce0758 100644 --- a/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var parent = (NavigationDialogHost)arg.Parameter; + NavigationDialogHost parent = (NavigationDialogHost)arg.Parameter; _parent = parent; diff --git a/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs b/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs index 6623e0aa0..67dc882e8 100644 --- a/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var (parent, accountManager, client, virtualFileSystem) = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; + (NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem) = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; _accountManager = accountManager; _horizonClient = client; _virtualFileSystem = virtualFileSystem; @@ -72,15 +72,15 @@ namespace Ryujinx.Ava.UI.Views.User public void LoadSaves() { ViewModel.Saves.Clear(); - var saves = new ObservableCollection(); - var saveDataFilter = SaveDataFilter.Make( + ObservableCollection saves = new(); + SaveDataFilter saveDataFilter = SaveDataFilter.Make( programId: default, saveType: SaveDataType.Account, new UserId((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low), saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new(); _horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); @@ -97,10 +97,10 @@ namespace Ryujinx.Ava.UI.Views.User for (int i = 0; i < readCount; i++) { - var save = saveDataInfo[i]; + SaveDataInfo save = saveDataInfo[i]; if (save.ProgramId.Value != 0) { - var saveModel = new SaveModel(save); + SaveModel saveModel = new(save); saves.Add(saveModel); } } @@ -135,7 +135,7 @@ namespace Ryujinx.Ava.UI.Views.User { if (button.DataContext is SaveModel saveModel) { - var result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DeleteUserSave], + UserResult result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DeleteUserSave], LocaleManager.Instance[LocaleKeys.IrreversibleActionNote], LocaleManager.Instance[LocaleKeys.InputDialogYes], LocaleManager.Instance[LocaleKeys.InputDialogNo], ""); diff --git a/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs b/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs index 3a155594c..4c7e64588 100644 --- a/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs @@ -62,7 +62,7 @@ namespace Ryujinx.Ava.UI.Windows int cheatAdded = 0; - var mods = new ModLoader.ModCache(); + ModLoader.ModCache mods = new(); ModLoader.QueryContentsDir(mods, new DirectoryInfo(Path.Combine(modsBasePath, "contents")), titleIdValue, []); @@ -71,7 +71,7 @@ namespace Ryujinx.Ava.UI.Windows CheatNode currentGroup = null; - foreach (var cheat in mods.Cheats) + foreach (ModLoader.Cheat cheat in mods.Cheats) { if (cheat.Path.FullName != currentCheatFile) { @@ -84,7 +84,7 @@ namespace Ryujinx.Ava.UI.Windows LoadedCheats.Add(currentGroup); } - var model = new CheatNode(cheat.Name, buildId, "", false, enabled.Contains($"{buildId}-{cheat.Name}")); + CheatNode model = new(cheat.Name, buildId, "", false, enabled.Contains($"{buildId}-{cheat.Name}")); currentGroup?.SubNodes.Add(model); cheatAdded++; @@ -109,9 +109,9 @@ namespace Ryujinx.Ava.UI.Windows List enabledCheats = []; - foreach (var cheats in LoadedCheats) + foreach (CheatNode cheats in LoadedCheats) { - foreach (var cheat in cheats.SubNodes) + foreach (CheatNode cheat in cheats.SubNodes) { if (cheat.IsEnabled) { diff --git a/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs b/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs index 89da05e5a..e128bfedd 100644 --- a/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs @@ -85,7 +85,7 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is DownloadableContentModel model) { @@ -93,7 +93,7 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is DownloadableContentModel model) { diff --git a/src/Ryujinx/UI/Windows/IconColorPicker.cs b/src/Ryujinx/UI/Windows/IconColorPicker.cs index dd6a55d4d..16a5afb30 100644 --- a/src/Ryujinx/UI/Windows/IconColorPicker.cs +++ b/src/Ryujinx/UI/Windows/IconColorPicker.cs @@ -57,8 +57,8 @@ namespace Ryujinx.Ava.UI.Windows public static SKColor GetColor(SKBitmap image) { - var colors = new PaletteColor[TotalColors]; - var dominantColorBin = new Dictionary(); + PaletteColor[] colors = new PaletteColor[TotalColors]; + Dictionary dominantColorBin = new(); var buffer = GetBuffer(image); @@ -87,7 +87,7 @@ namespace Ryujinx.Ava.UI.Windows byte cg = pixel.Green; byte cb = pixel.Blue; - var qck = GetQuantizedColorKey(cr, cg, cb); + int qck = GetQuantizedColorKey(cr, cg, cb); if (dominantColorBin.TryGetValue(qck, out int hitCount)) { @@ -112,7 +112,7 @@ namespace Ryujinx.Ava.UI.Windows for (i = 0; i < TotalColors; i++) { - var score = GetColorScore(dominantColorBin, maxHitCount, colors[i]); + int score = GetColorScore(dominantColorBin, maxHitCount, colors[i]); if (highScore < score) { @@ -141,17 +141,17 @@ namespace Ryujinx.Ava.UI.Windows private static int GetColorScore(Dictionary dominantColorBin, int maxHitCount, PaletteColor color) { - var hitCount = dominantColorBin[color.Qck]; - var balancedHitCount = BalanceHitCount(hitCount, maxHitCount); - var quantSat = (GetColorSaturation(color) >> SatQuantShift) << SatQuantShift; - var value = GetColorValue(color); + int hitCount = dominantColorBin[color.Qck]; + int balancedHitCount = BalanceHitCount(hitCount, maxHitCount); + int quantSat = (GetColorSaturation(color) >> SatQuantShift) << SatQuantShift; + int value = GetColorValue(color); // If the color is rarely used on the image, // then chances are that theres a better candidate, even if the saturation value // is high. By multiplying the saturation value with a weight, we can lower // it if the color is almost never used (hit count is low). - var satWeighted = quantSat; - var satWeight = balancedHitCount << 5; + int satWeighted = quantSat; + int satWeight = balancedHitCount << 5; if (satWeight < 0x100) { satWeighted = (satWeighted * satWeight) >> 8; @@ -159,7 +159,7 @@ namespace Ryujinx.Ava.UI.Windows // Compute score from saturation and dominance of the color. // We prefer more vivid colors over dominant ones, so give more weight to the saturation. - var score = ((satWeighted << 1) + balancedHitCount) * value; + int score = ((satWeighted << 1) + balancedHitCount) * value; return score; } diff --git a/src/Ryujinx/UI/Windows/MainWindow.axaml.cs b/src/Ryujinx/UI/Windows/MainWindow.axaml.cs index 93e3ed43b..2ee2458bb 100644 --- a/src/Ryujinx/UI/Windows/MainWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/MainWindow.axaml.cs @@ -179,9 +179,9 @@ namespace Ryujinx.Ava.UI.Windows { Dispatcher.UIThread.Post(() => { - var ldnGameDataArray = e.LdnData; + IEnumerable ldnGameDataArray = e.LdnData; ViewModel.LastLdnGameData = ldnGameDataArray; - foreach (var application in ViewModel.Applications) + foreach (ApplicationData application in ViewModel.Applications) { UpdateApplicationWithLdnData(application); } @@ -582,7 +582,7 @@ namespace Ryujinx.Ava.UI.Windows private void VolumeStatus_CheckedChanged(object sender, RoutedEventArgs e) { - var volumeSplitButton = sender as ToggleSplitButton; + ToggleSplitButton volumeSplitButton = sender as ToggleSplitButton; if (ViewModel.IsGameRunning) { if (volumeSplitButton is { IsChecked: false }) @@ -713,11 +713,11 @@ namespace Ryujinx.Ava.UI.Windows ApplicationLibrary.LoadApplications(ConfigurationState.Instance.UI.GameDirs); - var autoloadDirs = ConfigurationState.Instance.UI.AutoloadDirs.Value; + List autoloadDirs = ConfigurationState.Instance.UI.AutoloadDirs.Value; if (autoloadDirs.Count > 0) { - var updatesLoaded = ApplicationLibrary.AutoLoadTitleUpdates(autoloadDirs, out int updatesRemoved); - var dlcLoaded = ApplicationLibrary.AutoLoadDownloadableContents(autoloadDirs, out int dlcRemoved); + int updatesLoaded = ApplicationLibrary.AutoLoadTitleUpdates(autoloadDirs, out int updatesRemoved); + int dlcLoaded = ApplicationLibrary.AutoLoadDownloadableContents(autoloadDirs, out int dlcRemoved); ShowNewContentAddedDialog(dlcLoaded, dlcRemoved, updatesLoaded, updatesRemoved); } diff --git a/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs b/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs index 4558719cd..76988448d 100644 --- a/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Ava.UI.Windows { if (button.DataContext is ModModel model) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogWarning], LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogModManagerDeletionWarningMessage, model.Name), LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -84,7 +84,7 @@ namespace Ryujinx.Ava.UI.Windows private async void DeleteAll(object sender, RoutedEventArgs e) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogWarning], LocaleManager.Instance[LocaleKeys.DialogModManagerDeletionAllWarningMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -110,11 +110,11 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is ModModel model) { - var index = ViewModel.Mods.IndexOf(model); + int index = ViewModel.Mods.IndexOf(model); if (index != -1) { @@ -123,11 +123,11 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is ModModel model) { - var index = ViewModel.Mods.IndexOf(model); + int index = ViewModel.Mods.IndexOf(model); if (index != -1) { diff --git a/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs b/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs index f338bd7e9..9c4b2e914 100644 --- a/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is XCITrimmerFileModel applicationData) { @@ -89,7 +89,7 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is XCITrimmerFileModel applicationData) { diff --git a/src/Spv.Generator/Instruction.cs b/src/Spv.Generator/Instruction.cs index 88c75a465..17e185698 100644 --- a/src/Spv.Generator/Instruction.cs +++ b/src/Spv.Generator/Instruction.cs @@ -239,8 +239,8 @@ namespace Spv.Generator public override string ToString() { - var labels = _operandLabels.TryGetValue(Opcode, out var opLabels) ? opLabels : []; - var result = _resultType == null ? string.Empty : $"{_resultType} "; + string[] labels = _operandLabels.TryGetValue(Opcode, out string[] opLabels) ? opLabels : []; + string result = _resultType == null ? string.Empty : $"{_resultType} "; return $"{result}{Opcode}{_operands.ToString(labels)}"; } } diff --git a/src/Spv.Generator/InstructionOperands.cs b/src/Spv.Generator/InstructionOperands.cs index 18e04d8ab..38c2b1f2c 100644 --- a/src/Spv.Generator/InstructionOperands.cs +++ b/src/Spv.Generator/InstructionOperands.cs @@ -63,9 +63,9 @@ namespace Spv.Generator public readonly string ToString(string[] labels) { - var labeledParams = AllOperands.Zip(labels, (op, label) => $"{label}: {op}"); - var unlabeledParams = AllOperands.Skip(labels.Length).Select(op => op.ToString()); - var paramsToPrint = labeledParams.Concat(unlabeledParams); + IEnumerable labeledParams = AllOperands.Zip(labels, (op, label) => $"{label}: {op}"); + IEnumerable unlabeledParams = AllOperands.Skip(labels.Length).Select(op => op.ToString()); + IEnumerable paramsToPrint = labeledParams.Concat(unlabeledParams); return $"({string.Join(", ", paramsToPrint)})"; } } diff --git a/src/Spv.Generator/Module.cs b/src/Spv.Generator/Module.cs index bdd650854..026b9c5fb 100644 --- a/src/Spv.Generator/Module.cs +++ b/src/Spv.Generator/Module.cs @@ -85,7 +85,7 @@ namespace Spv.Generator public Instruction NewInstruction(Op opcode, uint id = Instruction.InvalidId, Instruction resultType = null) { - var result = _instPool.Allocate(); + Instruction result = _instPool.Allocate(); result.Set(opcode, id, resultType); return result; @@ -93,7 +93,7 @@ namespace Spv.Generator public Instruction AddExtInstImport(string import) { - var key = new DeterministicStringKey(import); + DeterministicStringKey key = new(import); if (_extInstImports.TryGetValue(key, out Instruction extInstImport)) { @@ -113,7 +113,7 @@ namespace Spv.Generator private void AddTypeDeclaration(Instruction instruction, bool forceIdAllocation) { - var key = new TypeDeclarationKey(instruction); + TypeDeclarationKey key = new(instruction); if (!forceIdAllocation) { @@ -214,7 +214,7 @@ namespace Spv.Generator or Op.OpConstantNull or Op.OpConstantComposite); - var key = new ConstantKey(constant); + ConstantKey key = new(constant); if (_constants.TryGetValue(key, out Instruction global)) {