Esempio n. 1
0
 /// <summary>
 /// Creates a new instance of the pool.
 /// </summary>
 /// <param name="context">GPU context that the pool belongs to</param>
 /// <param name="channel">GPU channel that the pool belongs to</param>
 /// <param name="address">Address of the pool in guest memory</param>
 /// <param name="maximumId">Maximum ID of the pool (equal to maximum minus one)</param>
 protected abstract T CreatePool(GpuContext context, GpuChannel channel, ulong address, int maximumId);
Esempio n. 2
0
 public Volume(VolumeStorage storage) : base(storage)
 {
     this._context       = storage.Context;
     this._volumeStorage = this.Storage as VolumeStorage;
 }
Esempio n. 3
0
 /// <summary>
 /// Constructs a new instance of the sampler pool.
 /// </summary>
 /// <param name="context">GPU context that the sampler pool belongs to</param>
 /// <param name="physicalMemory">Physical memory where the sampler descriptors are mapped</param>
 /// <param name="address">Address of the sampler pool in guest memory</param>
 /// <param name="maximumId">Maximum sampler ID of the sampler pool (equal to maximum samplers minus one)</param>
 public SamplerPool(GpuContext context, PhysicalMemory physicalMemory, ulong address, int maximumId) : base(context, physicalMemory, address, maximumId)
 {
     _forcedAnisotropy = GraphicsConfig.MaxAnisotropy;
 }
Esempio n. 4
0
        static void Main(string[] args)
        {
            // Based on https://github.com/gsvgit/Brahma.FSharp/tree/master/Source/BlackScholes
            const int   optionCount          = 1000000;
            const float riskFreeInterestRate = 0.02f;
            const float volatility           = 0.30f;
            const float A1 = 0.31938153f;
            const float A2 = -0.356563782f;
            const float A3 = 1.781477937f;
            const float A4 = -1.821255978f;
            const float A5 = 1.330274429f;

            // Helper functions
            Expression <Func <float, float> > k   = x => 1.0f / (1.0f + 0.2316419f * FMath.Abs(x));
            Expression <Func <float, float> > cnd = x =>
                                                    1.0f - 1.0f / FMath.Sqrt(2.0f * FMath.PI)
                                                    * FMath.Exp(-(FMath.Abs(x)) * (FMath.Abs(x)) / 2.0f) * (A1 * k.Invoke(x) + A2 * k.Invoke(x) * k.Invoke(x) + A3 * FMath.Pow(k.Invoke(x), 3)
                                                                                                            + A4 * FMath.Pow(k.Invoke(x), 4) + A5 * FMath.Pow(k.Invoke(x), 4));

            Expression <Func <float, float> > cumulativeNormalDistribution = x => (x < 0.0f) ? 1.0f - cnd.Invoke(x) : cnd.Invoke(x);

            Expression <Func <float, float, float, float> > d1 =
                (stockPrice, strikePrice, timeToExpirationYears) =>
                FMath.Log(stockPrice / strikePrice) + (riskFreeInterestRate + volatility * volatility / 2.0f) * timeToExpirationYears
                / (volatility * FMath.Sqrt(timeToExpirationYears));

            Expression <Func <float, float, float> > d2 =
                (_d1, timeToExpirationYears) => _d1 - volatility * FMath.Sqrt(timeToExpirationYears);

            Expression <Func <float, float, float, float, float, float> > blackScholesCallOption =
                (_d1, _d2, stockPrice, strikePrice, timeToExpirationYears) =>
                stockPrice *cumulativeNormalDistribution.Invoke(_d1) -
                strikePrice * FMath.Exp(-(riskFreeInterestRate) * timeToExpirationYears) * cumulativeNormalDistribution.Invoke(_d2);

            Expression <Func <float, float, float, float, float, float> > blackScholesPutOption =
                (_d1, _d2, stockPrice, strikePrice, timeToExpirationYears) =>
                strikePrice *FMath.Exp(-riskFreeInterestRate *timeToExpirationYears) *
                cumulativeNormalDistribution.Invoke(-_d2) - stockPrice * cumulativeNormalDistribution.Invoke(-_d1);

            // Init data
            var random = new System.Random();
            var data   = Enumerable.Range(1, optionCount).Select(_ => new InputData
            {
                Stock  = random.Random(5.0f, 30.0f),
                Strike = random.Random(1.0f, 100.0f),
                Times  = random.Random(0.25f, 10.0f)
            }).ToArray();

            // Main code
            using (GpuContext context = new GpuContext())
            {
                using (var _data = context.CreateGpuArray(data))
                {
                    var query =
                        (from d in _data.AsGpuQueryExpr()
                         let _d1 = d1.Invoke(d.Stock, d.Strike, d.Times)
                                   let _d2 = d2.Invoke(_d1, d.Times)
                                             select new OutPutData {
                        Call = blackScholesCallOption.Invoke(_d1, _d2, d.Stock, d.Strike, d.Times),
                        Put = blackScholesPutOption.Invoke(_d1, _d2, d.Stock, d.Strike, d.Times)
                    }).ToArray();

                    var result = context.Run(query);
                }
            }
        }
Esempio n. 5
0
 /// <summary>
 /// Constructs a new instance of the texture pool.
 /// </summary>
 /// <param name="context">GPU context that the texture pool belongs to</param>
 /// <param name="address">Address of the texture pool in guest memory</param>
 /// <param name="maximumId">Maximum texture ID of the texture pool (equal to maximum textures minus one)</param>
 public TexturePool(GpuContext context, ulong address, int maximumId) : base(context, address, maximumId)
 {
 }
Esempio n. 6
0
 public void RegisterCallback(GpuContext gpuContext, Action <SyncpointWaiterHandle> callback)
 {
     ref NvFence fence = ref NvFences[FenceCount - 1];
Esempio n. 7
0
        public Switch(
            VirtualFileSystem fileSystem,
            ContentManager contentManager,
            AccountManager accountManager,
            UserChannelPersistence userChannelPersistence,
            IRenderer renderer,
            IHardwareDeviceDriver audioDeviceDriver,
            MemoryConfiguration memoryConfiguration)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException(nameof(renderer));
            }

            if (audioDeviceDriver == null)
            {
                throw new ArgumentNullException(nameof(audioDeviceDriver));
            }

            if (userChannelPersistence == null)
            {
                throw new ArgumentNullException(nameof(userChannelPersistence));
            }

            UserChannelPersistence = userChannelPersistence;

            _memoryConfiguration = memoryConfiguration;

            AudioDeviceDriver = new CompatLayerHardwareDeviceDriver(audioDeviceDriver);

            Memory = new MemoryBlock(memoryConfiguration.ToDramSize(), MemoryAllocationFlags.Reserve);

            Gpu = new GpuContext(renderer);

            MemoryAllocator = new NvMemoryAllocator();

            Host1x = new Host1xDevice(Gpu.Synchronization);
            var nvdec = new NvdecDevice(Gpu.MemoryManager);
            var vic   = new VicDevice(Gpu.MemoryManager);

            Host1x.RegisterDevice(ClassId.Nvdec, nvdec);
            Host1x.RegisterDevice(ClassId.Vic, vic);

            nvdec.FrameDecoded += (FrameDecodedEventArgs e) =>
            {
                // FIXME:
                // Figure out what is causing frame ordering issues on H264.
                // For now this is needed as workaround.
                if (e.CodecId == CodecId.H264)
                {
                    vic.SetSurfaceOverride(e.LumaOffset, e.ChromaOffset, 0);
                }
                else
                {
                    vic.DisableSurfaceOverride();
                }
            };

            FileSystem = fileSystem;

            System = new Horizon(this, contentManager, accountManager, memoryConfiguration);
            System.InitializeServices();

            Statistics = new PerformanceStatistics();

            Hid = new Hid(this, System.HidStorage);
            Hid.InitDevices();

            Application = new ApplicationLoader(this, fileSystem, contentManager);

            TamperMachine = new TamperMachine();
        }
Esempio n. 8
0
 /// <summary>
 /// Constructs a new instance of the texture pool.
 /// </summary>
 /// <param name="context">GPU context that the texture pool belongs to</param>
 /// <param name="channel">GPU channel that the texture pool belongs to</param>
 /// <param name="address">Address of the texture pool in guest memory</param>
 /// <param name="maximumId">Maximum texture ID of the texture pool (equal to maximum textures minus one)</param>
 public TexturePool(GpuContext context, GpuChannel channel, ulong address, int maximumId) : base(context, channel.MemoryManager.Physical, address, maximumId)
 {
     _channel = channel;
 }
Esempio n. 9
0
        /// <summary>
        /// Constructs a new instance of the texture pool.
        /// </summary>
        /// <param name="context">GPU context that the texture pool belongs to</param>
        public TexturePoolCache(GpuContext context)
        {
            _context = context;

            _pools = new LinkedList <TexturePool>();
        }
Esempio n. 10
0
 /// <summary>
 /// Creates a new instance of the GPU memory accessor.
 /// </summary>
 /// <param name="context">GPU context that the memory accessor belongs to</param>
 public MemoryAccessor(GpuContext context)
 {
     _context = context;
 }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // Based on https://github.com/gsvgit/Brahma.FSharp/tree/master/Source/BlackScholes
            const int   optionCount          = 1000000;
            const float riskFreeInterestRate = 0.02f;
            const float volatility           = 0.30f;
            const float A1 = 0.31938153f;
            const float A2 = -0.356563782f;
            const float A3 = 1.781477937f;
            const float A4 = -1.821255978f;
            const float A5 = 1.330274429f;

            // Helper functions
            Expression <Func <float, float> > k = x => 1.0f / (1.0f + 0.2316419f * FMath.Abs(x));


            Expression <Func <float, float> > cnd = x =>
                                                    1.0f - 1.0f / FMath.Sqrt(2.0f * FMath.PI)
                                                    * FMath.Exp(-(FMath.Abs(x)) * (FMath.Abs(x)) / 2.0f) * (A1 * k.Invoke(x) + A2 * k.Invoke(x) * k.Invoke(x) + A3 * FMath.Pow(k.Invoke(x), 3)
                                                                                                            + A4 * FMath.Pow(k.Invoke(x), 4) + A5 * FMath.Pow(k.Invoke(x), 5));


            Expression <Func <float, float> > cumulativeNormalDistribution = x => (x < 0.0f) ? 1.0f - cnd.Invoke(x) : cnd.Invoke(x);

            Expression <Func <float, float, float, float> > d1 =
                (stockPrice, strikePrice, timeToExpirationYears) =>
                FMath.Log(stockPrice / strikePrice) + (riskFreeInterestRate + volatility * volatility / 2.0f) * timeToExpirationYears
                / (volatility * FMath.Sqrt(timeToExpirationYears));

            Expression <Func <float, float, float> > d2 =
                (_d1, timeToExpirationYears) => _d1 - volatility * FMath.Sqrt(timeToExpirationYears);

            Expression <Func <float, float, float, float, float, float> > blackScholesCallOption =
                (_d1, _d2, stockPrice, strikePrice, timeToExpirationYears) =>
                stockPrice *cumulativeNormalDistribution.Invoke(_d1) -
                strikePrice * FMath.Exp(-(riskFreeInterestRate) * timeToExpirationYears) * cumulativeNormalDistribution.Invoke(_d2);

            Expression <Func <float, float, float, float, float, float> > blackScholesPutOption =
                (_d1, _d2, stockPrice, strikePrice, timeToExpirationYears) =>
                strikePrice *FMath.Exp(-riskFreeInterestRate *timeToExpirationYears) *
                cumulativeNormalDistribution.Invoke(-_d2) - stockPrice * cumulativeNormalDistribution.Invoke(-_d1);

            // Init data
            var random = new System.Random();
            var data   = Enumerable.Range(1, optionCount).Select(_ => new InputData
            {
                Stock  = random.Random(5.0f, 30.0f),
                Strike = random.Random(1.0f, 100.0f),
                Times  = random.Random(0.25f, 10.0f)
            }).ToArray();
            // Main code
            Stopwatch timer = new Stopwatch();

            timer.Start();
            OutPutData[] results;
            using (GpuContext context = new GpuContext())
            {
                using (var _data = context.CreateGpuArray(data))
                {
                    var query =
                        (from d in _data.AsGpuQueryExpr()
                         let _d1 = d1.Invoke(d.Stock, d.Strike, d.Times)
                                   let _d2 = d2.Invoke(_d1, d.Times)
                                             select new OutPutData {
                        Call = blackScholesCallOption.Invoke(_d1, _d2, d.Stock, d.Strike, d.Times),
                        Put = blackScholesPutOption.Invoke(_d1, _d2, d.Stock, d.Strike, d.Times)
                    }).ToArray();

                    results = context.Run(query);
                }
            }
            timer.Stop();
            var elapsed = timer.ElapsedMilliseconds;

            Console.WriteLine("Black Scholes computed on Gpu in {0} milliseconds", elapsed);
            //String.Join<OutPutData>(", ", Enumerable.Range(1,120).
            //     Select(i => results.ElementAtOrDefault(i)).ToArray()));
            timer.Restart();
            var cpuResults = CpuBlackScholes(data);

            timer.Stop();
            elapsed = timer.ElapsedMilliseconds;
            Console.WriteLine("Black Scholes computed on Cpu in {0} milliseconds", elapsed);
            var resultsAreEqual = cpuResults.Zip(results, (a, b) => Tuple.Create(a, b)).All(pair => pair.Item1.IsEqual(pair.Item2));

            Console.WriteLine("Results calculated by cpu and gpu are {0}", resultsAreEqual ? "equal" : "not equal");
            Console.WriteLine("Results = {0}",
                              String.Join <Results>(", ", Enumerable.Range(1, 120).
                                                    Select(i => new Results()
            {
                Gpu = results.ElementAtOrDefault(i), Cpu = cpuResults.ElementAtOrDefault(i)
            }).ToArray()));
            Console.ReadLine();
        }
Esempio n. 12
0
 /// <summary>
 /// Creates a new GPU accessor.
 /// </summary>
 /// <param name="context">GPU context</param>
 public GpuAccessorBase(GpuContext context, ResourceCounts resourceCounts, int stageIndex)
 {
     _context        = context;
     _resourceCounts = resourceCounts;
     _stageIndex     = stageIndex;
 }
Esempio n. 13
0
        public Switch(HLEConfiguration configuration)
        {
            if (configuration.GpuRenderer == null)
            {
                throw new ArgumentNullException(nameof(configuration.GpuRenderer));
            }

            if (configuration.AudioDeviceDriver == null)
            {
                throw new ArgumentNullException(nameof(configuration.AudioDeviceDriver));
            }

            if (configuration.UserChannelPersistence == null)
            {
                throw new ArgumentNullException(nameof(configuration.UserChannelPersistence));
            }

            Configuration = configuration;

            UiHandler = configuration.HostUiHandler;

            AudioDeviceDriver = new CompatLayerHardwareDeviceDriver(configuration.AudioDeviceDriver);

            Memory = new MemoryBlock(configuration.MemoryConfiguration.ToDramSize());

            Gpu = new GpuContext(configuration.GpuRenderer);

            MemoryAllocator = new NvMemoryAllocator();

            Host1x = new Host1xDevice(Gpu.Synchronization);
            var nvdec = new NvdecDevice(Gpu.MemoryManager);
            var vic   = new VicDevice(Gpu.MemoryManager);

            Host1x.RegisterDevice(ClassId.Nvdec, nvdec);
            Host1x.RegisterDevice(ClassId.Vic, vic);

            nvdec.FrameDecoded += (FrameDecodedEventArgs e) =>
            {
                // FIXME:
                // Figure out what is causing frame ordering issues on H264.
                // For now this is needed as workaround.
                if (e.CodecId == CodecId.H264)
                {
                    vic.SetSurfaceOverride(e.LumaOffset, e.ChromaOffset, 0);
                }
                else
                {
                    vic.DisableSurfaceOverride();
                }
            };

            System = new Horizon(this);
            System.InitializeServices();

            Statistics = new PerformanceStatistics();

            Hid = new Hid(this, System.HidBaseAddress);
            Hid.InitDevices();

            Application = new ApplicationLoader(this);

            TamperMachine = new TamperMachine();

            Initialize();
        }
Esempio n. 14
0
 /// <summary>
 /// Constructs a new instance of the pool.
 /// </summary>
 /// <param name="context">GPU context that the texture pool belongs to</param>
 public PoolCache(GpuContext context)
 {
     _context = context;
     _pools   = new LinkedList <T>();
 }
Esempio n. 15
0
        /// <summary>
        /// Creates a new instance of the state updater.
        /// </summary>
        /// <param name="context">GPU context</param>
        /// <param name="channel">GPU channel</param>
        /// <param name="state">3D engine state</param>
        /// <param name="drawState">Draw state</param>
        public StateUpdater(GpuContext context, GpuChannel channel, DeviceStateWithShadow <ThreedClassState> state, DrawState drawState)
        {
            _context            = context;
            _channel            = channel;
            _state              = state;
            _drawState          = drawState;
            _currentProgramInfo = new ShaderProgramInfo[Constants.ShaderStages];

            // ShaderState must be the first, as other state updates depends on information from the currently bound shader.
            // Rasterizer and scissor states are checked by render target clear, their indexes
            // must be updated on the constants "RasterizerStateIndex" and "ScissorStateIndex" if modified.
            // The vertex buffer state may be forced dirty when a indexed draw starts, the "VertexBufferStateIndex"
            // constant must be updated if modified.
            // The order of the other state updates doesn't matter.
            _updateTracker = new StateUpdateTracker <ThreedClassState>(new[]
            {
                new StateUpdateCallbackEntry(UpdateShaderState,
                                             nameof(ThreedClassState.ShaderBaseAddress),
                                             nameof(ThreedClassState.ShaderState)),

                new StateUpdateCallbackEntry(UpdateRasterizerState, nameof(ThreedClassState.RasterizeEnable)),
                new StateUpdateCallbackEntry(UpdateScissorState, nameof(ThreedClassState.ScissorState)),

                new StateUpdateCallbackEntry(UpdateVertexBufferState,
                                             nameof(ThreedClassState.VertexBufferDrawState),
                                             nameof(ThreedClassState.VertexBufferInstanced),
                                             nameof(ThreedClassState.VertexBufferState),
                                             nameof(ThreedClassState.VertexBufferEndAddress)),

                new StateUpdateCallbackEntry(UpdateTfBufferState, nameof(ThreedClassState.TfBufferState)),
                new StateUpdateCallbackEntry(UpdateUserClipState, nameof(ThreedClassState.ClipDistanceEnable)),

                new StateUpdateCallbackEntry(UpdateRenderTargetState,
                                             nameof(ThreedClassState.RtColorState),
                                             nameof(ThreedClassState.RtDepthStencilState),
                                             nameof(ThreedClassState.RtControl),
                                             nameof(ThreedClassState.RtDepthStencilSize),
                                             nameof(ThreedClassState.RtDepthStencilEnable)),

                new StateUpdateCallbackEntry(UpdateDepthClampState, nameof(ThreedClassState.ViewVolumeClipControl)),

                new StateUpdateCallbackEntry(UpdateAlphaTestState,
                                             nameof(ThreedClassState.AlphaTestEnable),
                                             nameof(ThreedClassState.AlphaTestRef),
                                             nameof(ThreedClassState.AlphaTestFunc)),

                new StateUpdateCallbackEntry(UpdateDepthTestState,
                                             nameof(ThreedClassState.DepthTestEnable),
                                             nameof(ThreedClassState.DepthWriteEnable),
                                             nameof(ThreedClassState.DepthTestFunc)),

                new StateUpdateCallbackEntry(UpdateViewportTransform,
                                             nameof(ThreedClassState.DepthMode),
                                             nameof(ThreedClassState.ViewportTransform),
                                             nameof(ThreedClassState.ViewportExtents),
                                             nameof(ThreedClassState.YControl)),

                new StateUpdateCallbackEntry(UpdateDepthBiasState,
                                             nameof(ThreedClassState.DepthBiasState),
                                             nameof(ThreedClassState.DepthBiasFactor),
                                             nameof(ThreedClassState.DepthBiasUnits),
                                             nameof(ThreedClassState.DepthBiasClamp)),

                new StateUpdateCallbackEntry(UpdateStencilTestState,
                                             nameof(ThreedClassState.StencilBackMasks),
                                             nameof(ThreedClassState.StencilTestState),
                                             nameof(ThreedClassState.StencilBackTestState)),

                new StateUpdateCallbackEntry(UpdateSamplerPoolState,
                                             nameof(ThreedClassState.SamplerPoolState),
                                             nameof(ThreedClassState.SamplerIndex)),

                new StateUpdateCallbackEntry(UpdateTexturePoolState, nameof(ThreedClassState.TexturePoolState)),
                new StateUpdateCallbackEntry(UpdateVertexAttribState, nameof(ThreedClassState.VertexAttribState)),

                new StateUpdateCallbackEntry(UpdateLineState,
                                             nameof(ThreedClassState.LineWidthSmooth),
                                             nameof(ThreedClassState.LineSmoothEnable)),

                new StateUpdateCallbackEntry(UpdatePointState,
                                             nameof(ThreedClassState.PointSize),
                                             nameof(ThreedClassState.VertexProgramPointSize),
                                             nameof(ThreedClassState.PointSpriteEnable),
                                             nameof(ThreedClassState.PointCoordReplace)),

                new StateUpdateCallbackEntry(UpdatePrimitiveRestartState, nameof(ThreedClassState.PrimitiveRestartState)),

                new StateUpdateCallbackEntry(UpdateIndexBufferState,
                                             nameof(ThreedClassState.IndexBufferState),
                                             nameof(ThreedClassState.IndexBufferCount)),

                new StateUpdateCallbackEntry(UpdateFaceState, nameof(ThreedClassState.FaceState)),

                new StateUpdateCallbackEntry(UpdateRtColorMask,
                                             nameof(ThreedClassState.RtColorMaskShared),
                                             nameof(ThreedClassState.RtColorMask)),

                new StateUpdateCallbackEntry(UpdateBlendState,
                                             nameof(ThreedClassState.BlendIndependent),
                                             nameof(ThreedClassState.BlendConstant),
                                             nameof(ThreedClassState.BlendStateCommon),
                                             nameof(ThreedClassState.BlendEnableCommon),
                                             nameof(ThreedClassState.BlendEnable),
                                             nameof(ThreedClassState.BlendState)),

                new StateUpdateCallbackEntry(UpdateLogicOpState, nameof(ThreedClassState.LogicOpState))
            });
        }
Esempio n. 16
0
 /// <summary>
 /// Creates a new instance of a modified range list.
 /// </summary>
 /// <param name="context">GPU context that the buffer range list belongs to</param>
 public BufferModifiedRangeList(GpuContext context)
 {
     _context = context;
 }
Esempio n. 17
0
 /// <summary>
 /// Creates a new instance of the GPU memory manager.
 /// </summary>
 public MemoryManager(GpuContext context)
 {
     _context   = context;
     _pageTable = new ulong[PtLvl0Size][];
 }
Esempio n. 18
0
 /// <summary>
 /// Creates a new instance of the inline-to-memory engine class.
 /// </summary>
 /// <param name="context">GPU context</param>
 /// <param name="channel">GPU channel</param>
 public InlineToMemoryClass(GpuContext context, GpuChannel channel) : this(context, channel, true)
 {
 }
Esempio n. 19
0
 public void WaitForever(GpuContext gpuContext)
 {
     Wait(gpuContext, Timeout.InfiniteTimeSpan);
 }
Esempio n. 20
0
 public TextureDescriptorCapableGpuAccessor(GpuContext context)
 {
     _context = context;
 }
Esempio n. 21
0
 /// <summary>
 /// Creates a new instance of the GPU state accessor for graphics shader translation.
 /// </summary>
 /// <param name="context">GPU context</param>
 /// <param name="channel">GPU channel</param>
 /// <param name="state">Current GPU state</param>
 /// <param name="stageIndex">Graphics shader stage index (0 = Vertex, 4 = Fragment)</param>
 public GpuAccessor(GpuContext context, GpuChannel channel, GpuAccessorState state, int stageIndex) : base(context)
 {
     _channel    = channel;
     _state      = state;
     _stageIndex = stageIndex;
 }
Esempio n. 22
0
 /// <summary>
 /// Creates a new background disk cache writer.
 /// </summary>
 /// <param name="context">GPU context</param>
 /// <param name="hostStorage">Disk cache host storage</param>
 public BackgroundDiskCacheWriter(GpuContext context, DiskCacheHostStorage hostStorage)
 {
     _context               = context;
     _hostStorage           = hostStorage;
     _fileWriterWorkerQueue = new AsyncWorkQueue <CacheFileOperationTask>(ProcessTask, "Gpu.BackgroundDiskCacheWriter");
 }
Esempio n. 23
0
 /// <summary>
 /// Creates a new instance of the GPU state accessor for graphics shader translation.
 /// </summary>
 /// <param name="context">GPU context</param>
 /// <param name="state">Current GPU state</param>
 /// <param name="stageIndex">Graphics shader stage index (0 = Vertex, 4 = Fragment)</param>
 public GpuAccessor(GpuContext context, GpuState state, int stageIndex)
 {
     _context    = context;
     _state      = state;
     _stageIndex = stageIndex;
 }
Esempio n. 24
0
        public Switch(VirtualFileSystem fileSystem, ContentManager contentManager, UserChannelPersistence userChannelPersistence, IRenderer renderer, IAalOutput audioOut)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException(nameof(renderer));
            }

            if (audioOut == null)
            {
                throw new ArgumentNullException(nameof(audioOut));
            }

            if (userChannelPersistence == null)
            {
                throw new ArgumentNullException(nameof(userChannelPersistence));
            }

            UserChannelPersistence = userChannelPersistence;

            AudioOut = audioOut;

            Memory = new MemoryBlock(1UL << 32);

            Gpu = new GpuContext(renderer);

            MemoryAllocator = new NvMemoryAllocator();

            Host1x = new Host1xDevice(Gpu.Synchronization);
            var nvdec = new NvdecDevice(Gpu.MemoryManager);
            var vic   = new VicDevice(Gpu.MemoryManager);

            Host1x.RegisterDevice(ClassId.Nvdec, nvdec);
            Host1x.RegisterDevice(ClassId.Vic, vic);

            nvdec.FrameDecoded += (FrameDecodedEventArgs e) =>
            {
                // FIXME:
                // Figure out what is causing frame ordering issues on H264.
                // For now this is needed as workaround.
                if (e.CodecId == CodecId.H264)
                {
                    vic.SetSurfaceOverride(e.LumaOffset, e.ChromaOffset, 0);
                }
                else
                {
                    vic.DisableSurfaceOverride();
                }
            };

            FileSystem = fileSystem;

            System = new Horizon(this, contentManager);
            System.InitializeServices();

            Statistics = new PerformanceStatistics();

            Hid = new Hid(this, System.HidBaseAddress);
            Hid.InitDevices();

            Application = new ApplicationLoader(this, fileSystem, contentManager);
        }
Esempio n. 25
0
 public ArmProcessContextFactory(GpuContext gpu)
 {
     _gpu = gpu;
 }
Esempio n. 26
0
 private void AcquireBuffer(GpuContext ignored, object obj)
 {
     AcquireBuffer((TextureCallbackInformation)obj);
 }
Esempio n. 27
0
 public Volume(double[] array, Shape shape, GpuContext context) : base(new VolumeStorage(array, shape, context))
 {
     this._context       = context;
     this._volumeStorage = this.Storage as VolumeStorage;
 }
Esempio n. 28
0
        /// <summary>
        /// Migrates from the old cache format to the new one.
        /// </summary>
        /// <param name="context">GPU context</param>
        /// <param name="hostStorage">Disk cache host storage (used to create the new shader files)</param>
        /// <returns>Number of migrated shaders</returns>
        public static int MigrateFromLegacyCache(GpuContext context, DiskCacheHostStorage hostStorage)
        {
            string baseCacheDirectory = CacheHelper.GetBaseCacheDirectory(GraphicsConfig.TitleId);
            string cacheDirectory     = CacheHelper.GenerateCachePath(baseCacheDirectory, CacheGraphicsApi.Guest, "", "program");

            // If the directory does not exist, we have no old cache.
            // Exist early as the CacheManager constructor will create the directories.
            if (!Directory.Exists(cacheDirectory))
            {
                return(0);
            }

            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                CacheManager cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = cacheManager.GetGuestProgramList();

                for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
                {
                    Hash128 key = guestProgramList[programIndex];

                    byte[] guestProgram = cacheManager.GetGuestProgramByHash(ref key);

                    if (guestProgram == null)
                    {
                        Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                        continue;
                    }

                    ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                    ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                    if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                    {
                        Debug.Assert(cachedShaderEntries.Length == 1);

                        GuestShaderCacheEntry entry = cachedShaderEntries[0];

                        byte[] code = entry.Code.AsSpan(0, entry.Header.Size - entry.Header.Cb1DataSize).ToArray();

                        Span <byte> codeSpan = entry.Code;
                        byte[]      cb1Data  = codeSpan.Slice(codeSpan.Length - entry.Header.Cb1DataSize).ToArray();

                        ShaderProgramInfo info = new ShaderProgramInfo(
                            Array.Empty <BufferDescriptor>(),
                            Array.Empty <BufferDescriptor>(),
                            Array.Empty <TextureDescriptor>(),
                            Array.Empty <TextureDescriptor>(),
                            ShaderStage.Compute,
                            false,
                            false,
                            0,
                            0);

                        GpuChannelComputeState computeState = new GpuChannelComputeState(
                            entry.Header.GpuAccessorHeader.ComputeLocalSizeX,
                            entry.Header.GpuAccessorHeader.ComputeLocalSizeY,
                            entry.Header.GpuAccessorHeader.ComputeLocalSizeZ,
                            entry.Header.GpuAccessorHeader.ComputeLocalMemorySize,
                            entry.Header.GpuAccessorHeader.ComputeSharedMemorySize);

                        ShaderSpecializationState specState = new ShaderSpecializationState(computeState);

                        foreach (var td in entry.TextureDescriptors)
                        {
                            var handle = td.Key;
                            var data   = td.Value;

                            specState.RegisterTexture(
                                0,
                                handle,
                                -1,
                                data.UnpackFormat(),
                                data.UnpackSrgb(),
                                data.UnpackTextureTarget(),
                                data.UnpackTextureCoordNormalized());
                        }

                        CachedShaderStage   shader  = new CachedShaderStage(info, code, cb1Data);
                        CachedShaderProgram program = new CachedShaderProgram(null, specState, shader);

                        hostStorage.AddShader(context, program, ReadOnlySpan <byte> .Empty);
                    }
                    else
                    {
                        Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                        CachedShaderStage[]  shaders        = new CachedShaderStage[Constants.ShaderStages + 1];
                        List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                        TransformFeedbackDescriptorOld[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);

                        GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();

                        GuestGpuAccessorHeader accessorHeader = entries[0].Header.GpuAccessorHeader;

                        TessMode tessMode = new TessMode();

                        int  tessPatchType = accessorHeader.TessellationModePacked & 3;
                        int  tessSpacing   = (accessorHeader.TessellationModePacked >> 2) & 3;
                        bool tessCw        = (accessorHeader.TessellationModePacked & 0x10) != 0;

                        tessMode.Packed  = (uint)tessPatchType;
                        tessMode.Packed |= (uint)(tessSpacing << 4);

                        if (tessCw)
                        {
                            tessMode.Packed |= 0x100;
                        }

                        PrimitiveTopology topology = accessorHeader.PrimitiveTopology switch
                        {
                            InputTopology.Lines => PrimitiveTopology.Lines,
                            InputTopology.LinesAdjacency => PrimitiveTopology.LinesAdjacency,
                            InputTopology.Triangles => PrimitiveTopology.Triangles,
                            InputTopology.TrianglesAdjacency => PrimitiveTopology.TrianglesAdjacency,
                            _ => PrimitiveTopology.Points
                        };

                        GpuChannelGraphicsState graphicsState = new GpuChannelGraphicsState(
                            accessorHeader.StateFlags.HasFlag(GuestGpuStateFlags.EarlyZForce),
                            topology,
                            tessMode);

                        TransformFeedbackDescriptor[] tfdNew = null;

                        if (tfd != null)
                        {
                            tfdNew = new TransformFeedbackDescriptor[tfd.Length];

                            for (int tfIndex = 0; tfIndex < tfd.Length; tfIndex++)
                            {
                                Array32 <uint> varyingLocations     = new Array32 <uint>();
                                Span <byte>    varyingLocationsSpan = MemoryMarshal.Cast <uint, byte>(varyingLocations.ToSpan());
                                tfd[tfIndex].VaryingLocations.CopyTo(varyingLocationsSpan.Slice(0, tfd[tfIndex].VaryingLocations.Length));

                                tfdNew[tfIndex] = new TransformFeedbackDescriptor(
                                    tfd[tfIndex].BufferIndex,
                                    tfd[tfIndex].Stride,
                                    tfd[tfIndex].VaryingLocations.Length,
                                    ref varyingLocations);
                            }
                        }

                        ShaderSpecializationState specState = new ShaderSpecializationState(graphicsState, tfdNew);

                        for (int i = 0; i < entries.Length; i++)
                        {
                            GuestShaderCacheEntry entry = entries[i];

                            if (entry == null)
                            {
                                continue;
                            }

                            ShaderProgramInfo info = new ShaderProgramInfo(
                                Array.Empty <BufferDescriptor>(),
                                Array.Empty <BufferDescriptor>(),
                                Array.Empty <TextureDescriptor>(),
                                Array.Empty <TextureDescriptor>(),
                                (ShaderStage)(i + 1),
                                false,
                                false,
                                0,
                                0);

                            // NOTE: Vertex B comes first in the shader cache.
                            byte[] code  = entry.Code.AsSpan(0, entry.Header.Size - entry.Header.Cb1DataSize).ToArray();
                            byte[] code2 = entry.Header.SizeA != 0 ? entry.Code.AsSpan(entry.Header.Size, entry.Header.SizeA).ToArray() : null;

                            Span <byte> codeSpan = entry.Code;
                            byte[]      cb1Data  = codeSpan.Slice(codeSpan.Length - entry.Header.Cb1DataSize).ToArray();

                            shaders[i + 1] = new CachedShaderStage(info, code, cb1Data);

                            if (code2 != null)
                            {
                                shaders[0] = new CachedShaderStage(null, code2, cb1Data);
                            }

                            foreach (var td in entry.TextureDescriptors)
                            {
                                var handle = td.Key;
                                var data   = td.Value;

                                specState.RegisterTexture(
                                    i,
                                    handle,
                                    -1,
                                    data.UnpackFormat(),
                                    data.UnpackSrgb(),
                                    data.UnpackTextureTarget(),
                                    data.UnpackTextureCoordNormalized());
                            }
                        }

                        CachedShaderProgram program = new CachedShaderProgram(null, specState, shaders);

                        hostStorage.AddShader(context, program, ReadOnlySpan <byte> .Empty);
                    }
                }

                return(guestProgramList.Length);
            }

            return(0);
        }
    }
Esempio n. 29
0
 /// <summary>
 /// Creates a new instance of the semaphore updater.
 /// </summary>
 /// <param name="context">GPU context</param>
 /// <param name="channel">GPU channel</param>
 /// <param name="state">Channel state</param>
 public SemaphoreUpdater(GpuContext context, GpuChannel channel, DeviceStateWithShadow <ThreedClassState> state)
 {
     _context = context;
     _channel = channel;
     _state   = state;
 }
Esempio n. 30
0
 public Volume(float[] array, Shape shape) : base(new VolumeStorage(array, shape, GpuContext.Default))
 {
     this._context       = GpuContext.Default;
     this._volumeStorage = this.Storage as VolumeStorage;
 }